#!/bin/sh

# This spell installs bitcoin on almost any Linux platform, from source when possible, otherwise from precompiled binary.

# Set Bitcoin version
BITCOIN_VERSION=24.1

# Install Bitcoin from source
install_bitcoin_from_source() {
    say "Installing Bitcoin Core from source"
    if [ ! -e bitcoin-$BITCOIN_VERSION* ]; then
        wget https://bitcoincore.org/bin/bitcoin-core-$BITCOIN_VERSION/bitcoin-$BITCOIN_VERSION.tar.gz 
    fi
    . ./path_to_install_if_needed_script.sh boost
    tar -xvf bitcoin-$BITCOIN_VERSION.tar.gz
    sleep 1
    cd bitcoin-$BITCOIN_VERSION
    chmod +x autogen.sh
    ./autogen.sh
    ./configure --disable-wallet
    make 
    if [ $? -ne 0 ]; then
        return 1
    fi
    sudo make install
    cd ..
    return 0
}

# Install Bitcoin ARM precompiled binary
install_bitcoin_arm_binary() {
    say "Installing Bitcoin Core ARM precompiled binary"
    if [ ! -e bitcoin-$BITCOIN_VERSION* ]; then
        wget https://bitcoincore.org/bin/bitcoin-core-$BITCOIN_VERSION/bitcoin-$BITCOIN_VERSION-arm-linux-gnueabihf.tar.gz
        tar -xzf bitcoin-$BITCOIN_VERSION-arm-linux-gnueabihf.tar.gz
    fi
    sudo install -m 0755 -o root -g root -t /usr/local/bin bitcoin-$BITCOIN_VERSION/bin/*
}

# Install Bitcoin x86_64 precompiled binary
install_bitcoin_x86_64_binary() {
    say "Installing Bitcoin Core x86_64 precompiled binary"
    if [ ! -e bitcoin-$BITCOIN_VERSION* ]; then
        wget https://bitcoincore.org/bin/bitcoin-core-$BITCOIN_VERSION/bitcoin-$BITCOIN_VERSION-x86_64-linux-gnu.tar.gz
        tar -xzf bitcoin-$BITCOIN_VERSION-x86_64-linux-gnu.tar.gz
    fi
    sudo install -m 0755 -o root -g root -t /usr/local/bin bitcoin-$BITCOIN_VERSION/bin/*
}

# Install Bitcoin macOS precompiled binary
install_bitcoin_macos_binary() {
    say "Installing Bitcoin Core macOS precompiled binary"
    if [ ! -e bitcoin-$BITCOIN_VERSION* ]; then
        wget https://bitcoincore.org/bin/bitcoin-core-$BITCOIN_VERSION/bitcoin-$BITCOIN_VERSION-osx-signed.dmg
        hdiutil attach bitcoin-$BITCOIN_VERSION-osx-signed.dmg
        cp -R /Volumes/Bitcoin-Core/Bitcoin-Qt.app /Applications/
        hdiutil detach /Volumes/Bitcoin-Core
    fi
}

# Detect the operating system
OS=$(uname -s)

# Install Bitcoin based on the OS
case $OS in
    Darwin)
        install_bitcoin_macos_binary
        ;;
    Linux)
        ARCH=$(uname -m)
        case $ARCH in
            x86_64)
                if ! install_bitcoin_from_source; then
                    install_bitcoin_x86_64_binary
                fi
                ;;
            arm* | aarch64)
                install_bitcoin_arm_binary
                ;;
            *)
                say "Unsupported architecture: $ARCH"
                exit
        esac
        ;;
    *)
        say "Unsupported operating system: $OS"
        exit
esac