#!/usr/bin/env bash
# Update all service configurations with deployed contract addresses
# Usage: ./update-all-service-configs.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PASS="${PROXMOX_PASS:-L@kers2010}"

# Contract addresses
ORACLE_PROXY="0x3304b747e565a97ec8ac220b0b6a1f6ffdb837e6"
ORACLE_AGGREGATOR="0x99b3511a2d315a497c8112c1fdd8d508d4b1e506"
CCIP_ROUTER="0x8078A09637e47Fa5Ed34F626046Ea2094a5CDE5e"
CCIP_SENDER="0x105F8A15b819948a89153505762444Ee9f324684"
WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
RPC_URL="http://192.168.11.250:8545"
WS_URL="ws://192.168.11.250:8546"
CHAIN_ID="138"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

ssh_proxmox() {
    sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

log_info "========================================="
log_info "Update All Service Configurations"
log_info "========================================="
log_info ""

# Function to update .env file in container
update_env_file() {
    local vmid="$1"
    local env_file="$2"
    shift 2
    local updates="$@"
    
    log_info "Updating $env_file in VMID $vmid..."
    
    ssh_proxmox "pct exec $vmid -- bash -c '
        ENV_FILE=\"$env_file\"
        mkdir -p \$(dirname \"\$ENV_FILE\")
        touch \"\$ENV_FILE\"
        $updates
        echo \"✓ Updated \$ENV_FILE\"
    '" 2>&1 || log_warn "Failed to update $env_file in VMID $vmid"
}

# Oracle Publisher Service (VMID 3500)
if ssh_proxmox "pct list | grep -q '3500'"; then
    log_info "Updating Oracle Publisher Service (VMID 3500)..."
    update_env_file 3500 "/opt/oracle-publisher/.env" \
        "sed -i '/^ORACLE_ADDRESS=/d' \$ENV_FILE; echo \"ORACLE_ADDRESS=$ORACLE_PROXY\" >> \$ENV_FILE" \
        "sed -i '/^AGGREGATOR_ADDRESS=/d' \$ENV_FILE; echo \"AGGREGATOR_ADDRESS=$ORACLE_AGGREGATOR\" >> \$ENV_FILE" \
        "sed -i '/^RPC_URL=/d' \$ENV_FILE; echo \"RPC_URL=$RPC_URL\" >> \$ENV_FILE" \
        "sed -i '/^WS_URL=/d' \$ENV_FILE; echo \"WS_URL=$WS_URL\" >> \$ENV_FILE" \
        "sed -i '/^CHAIN_ID=/d' \$ENV_FILE; echo \"CHAIN_ID=$CHAIN_ID\" >> \$ENV_FILE"
    log_success "Oracle Publisher Service updated"
else
    log_warn "VMID 3500 (Oracle Publisher) not found, skipping..."
fi

# CCIP Monitor Service (VMID 3501)
if ssh_proxmox "pct list | grep -q '3501'"; then
    log_info "Updating CCIP Monitor Service (VMID 3501)..."
    update_env_file 3501 "/opt/ccip-monitor/.env" \
        "sed -i '/^CCIP_ROUTER_ADDRESS=/d' \$ENV_FILE; echo \"CCIP_ROUTER_ADDRESS=$CCIP_ROUTER\" >> \$ENV_FILE" \
        "sed -i '/^CCIP_SENDER_ADDRESS=/d' \$ENV_FILE; echo \"CCIP_SENDER_ADDRESS=$CCIP_SENDER\" >> \$ENV_FILE" \
        "sed -i '/^RPC_URL=/d' \$ENV_FILE; echo \"RPC_URL=$RPC_URL\" >> \$ENV_FILE" \
        "sed -i '/^WS_URL=/d' \$ENV_FILE; echo \"WS_URL=$WS_URL\" >> \$ENV_FILE" \
        "sed -i '/^CHAIN_ID=/d' \$ENV_FILE; echo \"CHAIN_ID=$CHAIN_ID\" >> \$ENV_FILE"
    log_success "CCIP Monitor Service updated"
else
    log_warn "VMID 3501 (CCIP Monitor) not found, skipping..."
fi

# Keeper Service (VMID 3502)
if ssh_proxmox "pct list | grep -q '3502'"; then
    log_info "Updating Keeper Service (VMID 3502)..."
    update_env_file 3502 "/opt/keeper/.env" \
        "sed -i '/^ORACLE_PRICE_FEED=/d' \$ENV_FILE; echo \"ORACLE_PRICE_FEED=$ORACLE_PROXY\" >> \$ENV_FILE" \
        "sed -i '/^RPC_URL=/d' \$ENV_FILE; echo \"RPC_URL=$RPC_URL\" >> \$ENV_FILE" \
        "sed -i '/^WS_URL=/d' \$ENV_FILE; echo \"WS_URL=$WS_URL\" >> \$ENV_FILE" \
        "sed -i '/^CHAIN_ID=/d' \$ENV_FILE; echo \"CHAIN_ID=$CHAIN_ID\" >> \$ENV_FILE"
    log_success "Keeper Service updated"
else
    log_warn "VMID 3502 (Keeper) not found, skipping..."
fi

# Financial Tokenization Service (VMID 3503)
if ssh_proxmox "pct list | grep -q '3503'"; then
    log_info "Updating Financial Tokenization Service (VMID 3503)..."
    update_env_file 3503 "/opt/tokenization/.env" \
        "sed -i '/^RPC_URL=/d' \$ENV_FILE; echo \"RPC_URL=$RPC_URL\" >> \$ENV_FILE" \
        "sed -i '/^WS_URL=/d' \$ENV_FILE; echo \"WS_URL=$WS_URL\" >> \$ENV_FILE" \
        "sed -i '/^CHAIN_ID=/d' \$ENV_FILE; echo \"CHAIN_ID=$CHAIN_ID\" >> \$ENV_FILE" \
        "sed -i '/^WETH9_ADDRESS=/d' \$ENV_FILE; echo \"WETH9_ADDRESS=$WETH9\" >> \$ENV_FILE" \
        "sed -i '/^WETH10_ADDRESS=/d' \$ENV_FILE; echo \"WETH10_ADDRESS=$WETH10\" >> \$ENV_FILE"
    log_success "Financial Tokenization Service updated"
else
    log_warn "VMID 3503 (Financial Tokenization) not found, skipping..."
fi

# Hyperledger Services
for vmid in 150 151; do
    if ssh_proxmox "pct list | grep -q '$vmid'"; then
        log_info "Updating Hyperledger Service (VMID $vmid)..."
        ssh_proxmox "pct exec $vmid -- bash -c '
            if [ -f /opt/firefly/docker-compose.yml ]; then
                sed -i \"s|FF_BLOCKCHAIN_RPC=.*|FF_BLOCKCHAIN_RPC=$RPC_URL|\" /opt/firefly/docker-compose.yml
                sed -i \"s|FF_BLOCKCHAIN_WS=.*|FF_BLOCKCHAIN_WS=$WS_URL|\" /opt/firefly/docker-compose.yml
                echo \"✓ Updated Firefly configuration\"
            fi
            if [ -f /opt/cacti/docker-compose.yml ]; then
                sed -i \"s|BESU_RPC_URL=.*|BESU_RPC_URL=$RPC_URL|\" /opt/cacti/docker-compose.yml
                sed -i \"s|BESU_WS_URL=.*|BESU_WS_URL=$WS_URL|\" /opt/cacti/docker-compose.yml
                echo \"✓ Updated Cacti configuration\"
            fi
        '" 2>&1 || log_warn "Failed to update VMID $vmid"
    fi
done

log_info ""
log_success "========================================="
log_success "Service Configuration Update Complete!"
log_success "========================================="
log_info ""
log_info "Next steps:"
log_info "1. Restart services to apply new configurations"
log_info "2. Verify services are connecting to contracts"
log_info "3. Check service logs for any errors"
log_info ""

