#!/bin/bash
#===============================================================================
#                    BTCPAY SERVER + TOR AUTOMATED INSTALLER
#===============================================================================
# Created: September 10, 2025
# Purpose: Automated BTCPay Server installation with Tor integration and pruned Bitcoin
# Target: Debian 13 VPS (works on Ubuntu too)
# Prerequisites: Docker installed, user in docker group

set -e  # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
BTCPAY_HOST="thebankofdebbie.giize.com"
BITCOIN_PRUNE_SIZE="10000"  # 10GB in MB
INSTALL_DIR="/opt/btcpayserver-docker"

# Logging function
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

info() {
    echo -e "${BLUE}[INFO] $1${NC}"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    error "Please run as root (use sudo su -)"
fi

log "Starting BTCPay Server + Tor Installation..."
log "Host: $BTCPAY_HOST"
log "Bitcoin Pruning: ${BITCOIN_PRUNE_SIZE}MB (~10GB)"

#===============================================================================
# PHASE 1: PREPARE INSTALLATION DIRECTORY
#===============================================================================

log "PHASE 1: Preparing installation directory..."

# Create and setup BTCPay directory
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# Clone BTCPay Server Docker repository
if [ -d ".git" ]; then
    log "BTCPay repository already exists, updating..."
    git pull
else
    log "Cloning BTCPay Server repository..."
    git clone https://github.com/btcpayserver/btcpayserver-docker.git .
fi

chmod +x btcpay-setup.sh

#===============================================================================
# PHASE 2: CONFIGURE ENVIRONMENT VARIABLES
#===============================================================================

log "PHASE 2: Configuring BTCPay environment..."

export BTCPAY_HOST="$BTCPAY_HOST"
export NBITCOIN_NETWORK="mainnet"
export BTCPAYGEN_CRYPTO1="btc"
export BTCPAYGEN_ADDITIONAL_FRAGMENTS="opt-add-tor"
export BTCPAY_ENABLE_SSH="true"

log "Environment configured:"
log "  BTCPAY_HOST: $BTCPAY_HOST"
log "  NETWORK: $NBITCOIN_NETWORK"
log "  CRYPTO: $BTCPAYGEN_CRYPTO1"
log "  TOR: $BTCPAYGEN_ADDITIONAL_FRAGMENTS"
log "  SSH: $BTCPAY_ENABLE_SSH"

#===============================================================================
# PHASE 3: RUN BTCPAY INSTALLATION
#===============================================================================

log "PHASE 3: Running BTCPay Server installation..."

# Run BTCPay setup
source ./btcpay-setup.sh -i

log "BTCPay Server installation completed"

#===============================================================================
# PHASE 4: CONFIGURE BITCOIN PRUNING
#===============================================================================

log "PHASE 4: Configuring Bitcoin pruning..."

# Stop Bitcoin to modify configuration
docker stop btcpayserver_bitcoind || warn "Bitcoin container not running"

# Add pruning to Docker Compose configuration
COMPOSE_FILE="$INSTALL_DIR/Generated/docker-compose.generated.yml"

if [ -f "$COMPOSE_FILE" ]; then
    # Add pruning to BITCOIN_EXTRA_ARGS in docker-compose.yml
    sed -i "/maxmempool=500/a\\        prune=$BITCOIN_PRUNE_SIZE" "$COMPOSE_FILE"
    
    log "Added pruning configuration to Docker Compose"
    
    # Verify the change
    if grep -q "prune=$BITCOIN_PRUNE_SIZE" "$COMPOSE_FILE"; then
        log "✅ Pruning configuration verified in Docker Compose"
    else
        warn "Failed to add pruning to Docker Compose, adding manually..."
        
        # Alternative method: modify the environment file
        echo "BITCOIN_EXTRA_ARGS=prune=$BITCOIN_PRUNE_SIZE" >> /opt/.env
    fi
else
    warn "Docker Compose file not found, will configure after restart"
fi

#===============================================================================
# PHASE 5: CONFIGURE TOR-ONLY BITCOIN NETWORKING
#===============================================================================

log "PHASE 5: Configuring Tor-only Bitcoin networking..."

# Additional Tor configuration will be applied when container starts
info "Bitcoin will be configured for:"
info "  - Pruned mode (${BITCOIN_PRUNE_SIZE}MB max storage)"
info "  - Tor-only networking (onlynet=onion via compose config)"
info "  - Automatic onion service creation"

#===============================================================================
# PHASE 6: START SERVICES
#===============================================================================

log "PHASE 6: Starting BTCPay services..."

# Start all services
btcpay-up.sh

# Wait for services to start
log "Waiting for services to initialize..."
sleep 30

#===============================================================================
# PHASE 7: VERIFY INSTALLATION
#===============================================================================

log "PHASE 7: Verifying installation..."

# Check Docker containers
log "Checking Docker containers:"
docker ps --format "table {{.Names}}\t{{.Status}}" | grep -E "(btcpay|bitcoin|tor|nginx)"

# Wait for Tor hidden services to be created
log "Waiting for Tor hidden services..."
sleep 30

# Display onion addresses
BTCPAY_ONION=""
BITCOIN_ONION=""

# Try to get onion addresses
if [ -f "/var/lib/docker/volumes/generated_tor_servicesdir/_data/BTCPayServer/hostname" ]; then
    BTCPAY_ONION=$(cat /var/lib/docker/volumes/generated_tor_servicesdir/_data/BTCPayServer/hostname)
fi

if [ -f "/var/lib/docker/volumes/generated_tor_servicesdir/_data/BTC-P2P/hostname" ]; then
    BITCOIN_ONION=$(cat /var/lib/docker/volumes/generated_tor_servicesdir/_data/BTC-P2P/hostname)
fi

#===============================================================================
# PHASE 8: CONFIGURE BITCOIN PRUNING POST-INSTALL
#===============================================================================

log "PHASE 8: Ensuring Bitcoin pruning is active..."

# Stop Bitcoin to clear any existing blockchain data if needed
docker stop btcpayserver_bitcoind 2>/dev/null || true

# Clear blockchain data to ensure pruning starts fresh
docker run --rm -v generated_bitcoin_datadir:/data alpine sh -c "
    if [ -d '/data/blocks' ] && [ -d '/data/chainstate' ]; then
        echo 'Clearing existing blockchain data for fresh pruned start...'
        rm -rf /data/blocks /data/chainstate /data/indexes
        echo 'Blockchain data cleared for pruned node'
    else
        echo 'No existing blockchain data found'
    fi
"

# Restart Bitcoin with pruning
docker start btcpayserver_bitcoind

log "Bitcoin restarted with pruning configuration"

#===============================================================================
# COMPLETION AND STATUS REPORT
#===============================================================================

log "==================================================================="
log "BTCPAY SERVER + TOR INSTALLATION COMPLETED!"
log "==================================================================="
log ""
log "🌐 ACCESS INFORMATION:"
log "  Clearnet: https://$BTCPAY_HOST"
if [ -n "$BTCPAY_ONION" ]; then
    log "  Tor Onion: http://$BTCPAY_ONION"
else
    log "  Tor Onion: Generating... (check in 5 minutes)"
fi
log ""
log "🔒 SECURITY FEATURES:"
log "  ✅ Tor hidden service for BTCPay Server"
log "  ✅ Bitcoin P2P over Tor network"
log "  ✅ Pruned Bitcoin node (${BITCOIN_PRUNE_SIZE}MB max)"
log "  ✅ SSL/HTTPS with Let's Encrypt"
log ""
log "📊 STORAGE MANAGEMENT:"
log "  Bitcoin blockchain: ~10GB maximum (pruned)"
log "  Total estimated usage: ~20GB for full setup"
log "  Safe for 387GB VPS with plenty of room"
log ""
log "⚡ NEXT STEPS:"
log "  1. Wait for Bitcoin initial sync (12-24 hours over Tor)"
log "  2. Access BTCPay via Tor Browser or clearnet"
log "  3. Complete BTCPay setup wizard"
log "  4. Test payment processing"
log ""
if [ -n "$BTCPAY_ONION" ]; then
    log "🧅 YOUR TOR ADDRESSES:"
    log "  BTCPay: $BTCPAY_ONION"
    if [ -n "$BITCOIN_ONION" ]; then
        log "  Bitcoin P2P: $BITCOIN_ONION"
    fi
fi
log ""
log "🔧 USEFUL COMMANDS:"
log "  btcpay-restart.sh    - Restart all services"
log "  btcpay-update.sh     - Update BTCPay Server"
log "  docker logs btcpayserver_bitcoind  - Check Bitcoin sync"
log ""

# Show current disk usage
log "💾 CURRENT DISK USAGE:"
df -h / | grep -v tmpfs

# Create monitoring script
log "Creating monitoring script..."
cat > /home/ubuntu/monitor-btcpay.sh << 'EOF'
#!/bin/bash
echo "=== BTCPay + Bitcoin Status - $(date) ==="
echo ""
echo "Docker Containers:"
docker ps --format "table {{.Names}}\t{{.Status}}" | grep -E "(btcpay|bitcoin|tor)"
echo ""
echo "Bitcoin Sync Status:"
docker exec btcpayserver_bitcoind bitcoin-cli getblockchaininfo 2>/dev/null | jq '{blocks, headers, pruned, verificationprogress}' || echo "Bitcoin still starting..."
echo ""
echo "Disk Usage:"
echo "Bitcoin data: $(docker exec btcpayserver_bitcoind du -sh /data/ 2>/dev/null || echo "N/A")"
echo "Total disk: $(df -h / | grep -v Filesystem | awk '{print $3 " used / " $2 " total (" $5 " full)"}')"
echo ""
echo "Tor Onion Addresses:"
echo "BTCPay: $(cat /var/lib/docker/volumes/generated_tor_servicesdir/_data/BTCPayServer/hostname 2>/dev/null || echo "Not ready")"
echo "Bitcoin: $(cat /var/lib/docker/volumes/generated_tor_servicesdir/_data/BTC-P2P/hostname 2>/dev/null || echo "Not ready")"
EOF

chmod +x /home/ubuntu/monitor-btcpay.sh
chown ubuntu:ubuntu /home/ubuntu/monitor-btcpay.sh

log "✅ Installation complete! Use /home/ubuntu/monitor-btcpay.sh to check status"

warn "IMPORTANT: Bitcoin will sync over Tor (slower but private)"
warn "Monitor disk usage, though pruning should keep it under 10GB"