#!/bin/bash
#
# Archipelago Main Menu
# Interactive setup wizard for Archipelago Bitcoin Node OS
#

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Install required tools on first run (for live mode)
install_required_tools() {
    if [ -f /tmp/.archipelago-tools-installed ]; then
        return 0
    fi
    
    # Check if we need to install tools
    local NEED_TOOLS=0
    for tool in parted debootstrap mkfs.ext4 mkfs.vfat; do
        if ! command -v $tool >/dev/null 2>&1; then
            NEED_TOOLS=1
            break
        fi
    done
    
    if [ $NEED_TOOLS -eq 1 ]; then
        echo ""
        echo "  📦 Installing required tools (first run)..."
        echo ""
        sudo apt-get update -qq 2>/dev/null
        sudo apt-get install -y parted debootstrap dosfstools e2fsprogs 2>/dev/null
        echo "  ✅ Tools installed"
        echo ""
        sleep 1
    fi
    
    touch /tmp/.archipelago-tools-installed
}

# Run tool installation at startup
install_required_tools

show_banner() {
    clear
    echo ""
    echo "  ╔═══════════════════════════════════════════════════════════╗"
    echo "  ║                                                           ║"
    echo "  ║   🏝️  ARCHIPELAGO BITCOIN NODE OS                         ║"
    echo "  ║                                                           ║"
    echo "  ║   Your sovereign Bitcoin infrastructure                   ║"
    echo "  ║                                                           ║"
    echo "  ╚═══════════════════════════════════════════════════════════╝"
    echo ""
}

show_status() {
    echo "  System Status:"
    echo "  ─────────────────────────────────────────────────────────────"
    
    # Check if we're in live mode
    if [ -d /run/live ]; then
        echo "  Mode:        🔴 Live (changes won't persist)"
    else
        echo "  Mode:        🟢 Installed"
    fi
    
    # Check Podman
    if command -v podman >/dev/null 2>&1; then
        echo "  Podman:      🟢 Installed"
    else
        echo "  Podman:      🔴 Not installed"
    fi
    
    # Check Bitcoin Core
    if podman ps 2>/dev/null | grep -q bitcoind; then
        BLOCKS=$(podman exec bitcoind bitcoin-cli getblockcount 2>/dev/null || echo "syncing")
        echo "  Bitcoin:     🟢 Running (blocks: $BLOCKS)"
    elif podman ps -a 2>/dev/null | grep -q bitcoind; then
        echo "  Bitcoin:     🟡 Stopped"
    else
        echo "  Bitcoin:     ⚪ Not configured"
    fi
    
    # Check LND
    if podman ps 2>/dev/null | grep -q lnd; then
        echo "  Lightning:   🟢 Running"
    elif podman ps -a 2>/dev/null | grep -q lnd; then
        echo "  Lightning:   🟡 Stopped"
    else
        echo "  Lightning:   ⚪ Not configured"
    fi
    
    echo ""
}

main_menu() {
    while true; do
        show_banner
        show_status
        
        # Show Web UI URL prominently
        IP=$(hostname -I 2>/dev/null | awk '{print $1}')
        [ -z "$IP" ] && IP=$(ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1' | head -1)
        
        echo "  ┌─────────────────────────────────────────────────────────────┐"
        if [ -n "$IP" ]; then
            # Check if backend is running
            if pgrep -f "archipelago" >/dev/null 2>&1; then
                echo "  │  🌐 Web UI:  http://$IP:5678  (running)                 │"
            else
                echo "  │  🌐 Web UI:  http://$IP:5678  (not started)             │"
            fi
            echo "  │  📡 SSH:     ssh user@$IP  (password: archipelago)      │"
        else
            echo "  │  🌐 Web UI:  (no network)                                 │"
        fi
        echo "  └─────────────────────────────────────────────────────────────┘"
        echo ""
        
        echo "  Main Menu:"
        echo "  ─────────────────────────────────────────────────────────────"
        echo ""
        echo "  r) Refresh                - Update IP/status (no restart needed)"
        echo "  w) Open Web UI            - Launch graphical interface"
        echo ""
        echo "  1) Install to Disk        - Permanently install Archipelago"
        echo "  2) Setup Bitcoin Core     - Configure Bitcoin full node"
        echo "  3) Setup Lightning (LND)  - Configure Lightning Network"
        echo "  4) Setup BTCPay Server    - Bitcoin payment processor"
        echo "  5) View Logs              - Monitor running services"
        echo "  6) Network Settings       - Configure networking"
        echo "  7) System Info            - View system information"
        echo ""
        echo "  q) Quit"
        echo ""
        read -p "  Select option: " choice
        
        case $choice in
            r|R)
                # Refresh - just loop again to show updated IP/status
                ;;
            w|W)
                echo ""
                # Start the real backend on port 5678
                if command -v archipelago >/dev/null 2>&1; then
                    if pgrep -f "archipelago" >/dev/null 2>&1; then
                        echo "  ✅ Archipelago backend already running on port 5678"
                    else
                        echo "  🚀 Starting Archipelago backend on port 5678..."
                        nohup archipelago >/tmp/archipelago.log 2>&1 &
                        sleep 2
                        if pgrep -f "archipelago" >/dev/null 2>&1; then
                            echo "  ✅ Backend started!"
                        else
                            echo "  ⚠️  Failed to start backend. Check /tmp/archipelago.log"
                        fi
                    fi
                    IP=$(hostname -I 2>/dev/null | awk '{print $1}')
                    echo ""
                    echo "  ┌─────────────────────────────────────────────────────────────┐"
                    echo "  │  🌐 Open in browser:  http://$IP:5678                   │"
                    echo "  └─────────────────────────────────────────────────────────────┘"
                else
                    echo "  ⚠️  Archipelago binary not found at /usr/local/bin/archipelago"
                    echo ""
                    echo "  Try running:"
                    echo "    sudo cp /run/live/medium/archipelago/bin/archipelago /usr/local/bin/"
                fi
                echo ""
                read -p "  Press Enter to continue..."
                ;;
            1)
                if [ -f "$SCRIPT_DIR/install-to-disk.sh" ]; then
                    sudo bash "$SCRIPT_DIR/install-to-disk.sh"
                else
                    echo "Installer not found. Running from: $SCRIPT_DIR"
                fi
                read -p "Press Enter to continue..."
                ;;
            2)
                if [ -f "$SCRIPT_DIR/setup-bitcoin.sh" ]; then
                    bash "$SCRIPT_DIR/setup-bitcoin.sh"
                else
                    echo "Bitcoin setup script not found."
                fi
                read -p "Press Enter to continue..."
                ;;
            3)
                if [ -f "$SCRIPT_DIR/setup-lnd.sh" ]; then
                    bash "$SCRIPT_DIR/setup-lnd.sh"
                else
                    echo "LND setup script not found."
                fi
                read -p "Press Enter to continue..."
                ;;
            4)
                setup_btcpay
                read -p "Press Enter to continue..."
                ;;
            5)
                view_logs
                ;;
            6)
                network_settings
                read -p "Press Enter to continue..."
                ;;
            7)
                system_info
                read -p "Press Enter to continue..."
                ;;
            q|Q)
                echo ""
                echo "  Goodbye! 🏝️"
                echo ""
                exit 0
                ;;
            *)
                echo "Invalid option"
                sleep 1
                ;;
        esac
    done
}

setup_btcpay() {
    show_banner
    echo "  BTCPay Server Setup"
    echo "  ─────────────────────────────────────────────────────────────"
    echo ""
    echo "  BTCPay Server is a self-hosted Bitcoin payment processor."
    echo ""
    
    if ! podman ps | grep -q bitcoind; then
        echo "  ⚠️  Bitcoin Core must be running first."
        return
    fi
    
    read -p "  Setup BTCPay Server? [y/N]: " SETUP
    if [[ ! "$SETUP" =~ ^[Yy]$ ]]; then
        return
    fi
    
    echo ""
    echo "  🐳 Pulling BTCPay Server image..."
    podman pull docker.io/btcpayserver/btcpayserver:latest
    
    # Create data directory
    mkdir -p ~/.btcpay
    
    echo ""
    echo "  BTCPay Server setup is more complex and typically uses docker-compose."
    echo "  For a full setup, visit: https://docs.btcpayserver.org"
    echo ""
}

view_logs() {
    show_banner
    echo "  View Logs"
    echo "  ─────────────────────────────────────────────────────────────"
    echo ""
    echo "  1) Bitcoin Core logs"
    echo "  2) LND logs"
    echo "  3) System logs"
    echo "  b) Back"
    echo ""
    read -p "  Select: " choice
    
    case $choice in
        1)
            if podman ps -a | grep -q bitcoind; then
                podman logs -f --tail 50 bitcoind
            else
                echo "Bitcoin Core not running"
                read -p "Press Enter..."
            fi
            ;;
        2)
            if podman ps -a | grep -q lnd; then
                podman logs -f --tail 50 lnd
            else
                echo "LND not running"
                read -p "Press Enter..."
            fi
            ;;
        3)
            journalctl -f
            ;;
    esac
}

network_settings() {
    show_banner
    echo "  Network Settings"
    echo "  ─────────────────────────────────────────────────────────────"
    echo ""
    
    # Show current IP
    IP=$(hostname -I | awk '{print $1}')
    echo "  Current IP: $IP"
    echo ""
    
    # Show network interfaces
    echo "  Network Interfaces:"
    ip -br addr | grep -v "^lo" | while read line; do
        echo "    $line"
    done
    echo ""
    
    echo "  Ports in use:"
    echo "    8332  - Bitcoin RPC"
    echo "    8333  - Bitcoin P2P"
    echo "    9735  - Lightning P2P"
    echo "    10009 - Lightning gRPC"
    echo "    8080  - Lightning REST"
    echo ""
}

system_info() {
    show_banner
    echo "  System Information"
    echo "  ─────────────────────────────────────────────────────────────"
    echo ""
    echo "  Hostname:    $(hostname)"
    echo "  Kernel:      $(uname -r)"
    echo "  Uptime:      $(uptime -p)"
    echo ""
    echo "  CPU:         $(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)"
    echo "  Memory:      $(free -h | grep Mem | awk '{print $2}') total, $(free -h | grep Mem | awk '{print $3}') used"
    echo ""
    echo "  Disk Usage:"
    df -h / | tail -1 | awk '{print "    Root: " $3 " / " $2 " (" $5 " used)"}'
    if [ -d ~/.bitcoin ]; then
        echo "    Bitcoin: $(du -sh ~/.bitcoin 2>/dev/null | cut -f1)"
    fi
    echo ""
    
    # Container status
    echo "  Containers:"
    if command -v podman >/dev/null 2>&1; then
        podman ps --format "    {{.Names}}: {{.Status}}" 2>/dev/null || echo "    No containers running"
    fi
    echo ""
}

# Run main menu
main_menu
