#!/bin/sh

# Function to check if a package is installed in Debian-based distributions
is_deb_package_installed() {
    dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -c "ok installed"
}

# Function to check if a package is installed in Redhat-based distributions
is_rpm_package_installed() {
    rpm -q "$1" &> /dev/null
}

# Function to check if a package is installed in Arch-based distributions
is_arch_package_installed() {
    pacman -Q "$1" &> /dev/null
}

# Uninstall Bitcoin from source
uninstall_bitcoin_from_source() {
    say "Uninstalling Bitcoin Core installed from source"
    sudo make uninstall
}

# Uninstall Bitcoin package
uninstall_bitcoin_package() {
    say "Uninstalling Bitcoin Core package"

    # Detect the operating system's package manager
    if command -v apt &> /dev/null; then
        if is_deb_package_installed bitcoin; then
            sudo apt-get remove -y bitcoin
        fi
    elif command -v dnf &> /dev/null; then
        if is_rpm_package_installed bitcoin; then
            sudo dnf remove -y bitcoin
        fi
    elif command -v pacman &> /dev/null; then
        if is_arch_package_installed bitcoin; then
            sudo pacman -Rns bitcoin --noconfirm
        fi
    elif command -v brew &> /dev/null; then
        if brew list --cask bitcoin-core; then
            brew uninstall --cask bitcoin-core
        fi
    else
        say "Unsupported package manager"
        exit 1
    fi
}

# Uninstall Bitcoin
uninstall_bitcoin() {
    read -p "This will uninstall Bitcoin Core and might delete your wallet data. Are you sure? (Y/n) " yn
    case $yn in
        [Yy]* )
            uninstall_bitcoin_from_source
            uninstall_bitcoin_package
            ;;
        [Nn]* )
            say "Uninstallation cancelled"
            ;;
        * )
            say "Invalid input. Please answer with Y (yes) or N (no)"
            uninstall_bitcoin
            ;;
    esac
}

# Start the uninstallation
uninstall_bitcoin