#!/bin/bash
# Fix all remaining issues: Redis, Vault, Web3Signer keys, Allowlist
# Usage: ./scripts/fix-all-remaining-issues.sh

set -e

PROXMOX_HOST="192.168.11.11"
WEB3SIGNER_IP="192.168.11.111"
REDIS_CONTAINER="106"
VAULT_CONTAINER="108"
WEB3SIGNER_CONTAINER="107"

echo "═══════════════════════════════════════════════════════════════"
echo "🔧 FIXING ALL REMAINING ISSUES"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Step 1: Fix Redis
echo "Step 1: Fixing Redis..."
echo "  Checking Redis status..."
REDIS_STATUS=$(ssh root@$PROXMOX_HOST "pct exec $REDIS_CONTAINER -- systemctl is-active redis-server" 2>&1 || echo "inactive")
if [ "$REDIS_STATUS" != "active" ]; then
    echo "  Starting Redis..."
    ssh root@$PROXMOX_HOST "pct exec $REDIS_CONTAINER -- systemctl start redis-server && sleep 2" 2>&1
fi
REDIS_PING=$(ssh root@$PROXMOX_HOST "pct exec $REDIS_CONTAINER -- redis-cli ping" 2>&1 || echo "not responding")
if [ "$REDIS_PING" = "PONG" ]; then
    echo "  ✅ Redis: Running"
else
    echo "  ⚠️  Redis: $REDIS_PING"
fi

# Step 2: Fix Vault
echo ""
echo "Step 2: Fixing Vault..."
echo "  Checking Vault status..."
VAULT_STATUS=$(ssh root@$PROXMOX_HOST "pct exec $VAULT_CONTAINER -- systemctl is-active vault" 2>&1 || echo "inactive")
if [ "$VAULT_STATUS" != "active" ]; then
    echo "  Starting Vault..."
    ssh root@$PROXMOX_HOST "pct exec $VAULT_CONTAINER -- systemctl start vault && sleep 2" 2>&1
fi
VAULT_HEALTH=$(curl -s -m 5 http://192.168.11.112:8200/v1/sys/health 2>&1 | jq -r '.status' 2>/dev/null || echo "not responding")
if [ "$VAULT_HEALTH" = "active" ] || [ "$VAULT_HEALTH" = "standby" ]; then
    echo "  ✅ Vault: $VAULT_HEALTH"
else
    echo "  ⚠️  Vault: $VAULT_HEALTH"
fi

# Step 3: Fix Web3Signer keys
echo ""
echo "Step 3: Fixing Web3Signer keys..."
echo "  Ensuring service is enabled and running..."
ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- bash -c 'systemctl daemon-reload && systemctl enable web3signer.service && systemctl restart web3signer.service && sleep 5'" 2>&1

echo "  Checking keys location..."
KEYS_COUNT=$(ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- ls -1 /opt/web3signer/data/keys/*.json 2>/dev/null | wc -l" 2>&1 || echo "0")
echo "  Keys found in directory: $KEYS_COUNT"

if [ "$KEYS_COUNT" -gt 0 ]; then
    echo "  Keys exist, checking if Web3Signer loads them..."
    sleep 3
    KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>&1 || echo "[]")
    if [ "$KEYS" != "[]" ] && [ -n "$KEYS" ]; then
        KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
        if [ "$KEY_COUNT" -gt 0 ]; then
            echo "  ✅ Keys loaded: $KEY_COUNT"
            ADDRESSES=$(echo "$KEYS" | jq -r '.[]' | tr '\n' ',' | sed 's/,$//')
            echo "$ADDRESSES" > /tmp/web3signer-addresses.txt
        else
            echo "  ⚠️  Keys not loaded yet, checking logs..."
            ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- journalctl -u web3signer.service -n 20 --no-pager" 2>&1 | grep -i "key\|signer\|error" | tail -10
        fi
    else
        echo "  ⚠️  Keys not loaded, checking Web3Signer logs..."
        ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- journalctl -u web3signer.service -n 30 --no-pager" 2>&1 | tail -15
    fi
else
    echo "  ⚠️  No keys found in /opt/web3signer/data/keys/"
    echo "  Keys need to be generated and loaded first"
fi

# Step 4: Configure allowlist
echo ""
echo "Step 4: Configuring wallet allowlist..."
if [ -f /tmp/web3signer-addresses.txt ]; then
    ADDRESSES=$(cat /tmp/web3signer-addresses.txt)
    if [ -n "$ADDRESSES" ]; then
        echo "  Configuring allowlist with addresses: $ADDRESSES"
        cd "$(dirname "$0")/.."
        ./scripts/configure-wallet-allowlist.sh "$ADDRESSES" 2>&1 || echo "  ⚠️  Allowlist configuration had issues"
    else
        echo "  ⚠️  No addresses available for allowlist"
    fi
else
    # Try to get addresses from API
    KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>&1 || echo "[]")
    if [ "$KEYS" != "[]" ] && [ -n "$KEYS" ]; then
        ADDRESSES=$(echo "$KEYS" | jq -r '.[]' | tr '\n' ',' | sed 's/,$//')
        if [ -n "$ADDRESSES" ]; then
            echo "  Configuring allowlist with addresses from API..."
            cd "$(dirname "$0")/.."
            ./scripts/configure-wallet-allowlist.sh "$ADDRESSES" 2>&1 || echo "  ⚠️  Allowlist configuration had issues"
        else
            echo "  ⚠️  No addresses available (keys not loaded)"
        fi
    else
        echo "  ⚠️  Keys not loaded, cannot configure allowlist"
    fi
fi

# Step 5: Restart translators to pick up allowlist
echo ""
echo "Step 5: Restarting translator services..."
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    echo "  Restarting $IP..."
    ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl restart rpc-translator-138.service && sleep 2" 2>&1 || echo "  ⚠️  Failed to restart $IP"
done

# Step 6: Final status check
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "📊 FINAL STATUS CHECK"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Redis
REDIS_PING=$(ssh root@$PROXMOX_HOST "pct exec $REDIS_CONTAINER -- redis-cli ping" 2>&1 || echo "not responding")
echo "Redis: $([ "$REDIS_PING" = "PONG" ] && echo "✅ Running" || echo "❌ $REDIS_PING")"

# Web3Signer
WEB3SIGNER_HEALTH=$(curl -s -m 5 http://$WEB3SIGNER_IP:9000/upcheck 2>&1 || echo "not responding")
KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>&1 || echo "[]")
KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
echo "Web3Signer: $([ "$WEB3SIGNER_HEALTH" = "OK" ] && echo "✅ Health OK" || echo "❌ $WEB3SIGNER_HEALTH"), Keys: $([ "$KEY_COUNT" -gt 0 ] && echo "✅ $KEY_COUNT loaded" || echo "⚠️  Not loaded")"

# Vault
VAULT_HEALTH=$(curl -s -m 5 http://192.168.11.112:8200/v1/sys/health 2>&1 | jq -r '.status' 2>/dev/null || echo "not responding")
echo "Vault: $([ "$VAULT_HEALTH" = "active" ] || [ "$VAULT_HEALTH" = "standby" ] && echo "✅ $VAULT_HEALTH" || echo "⚠️  $VAULT_HEALTH")"

# Translators
echo ""
echo "Translators:"
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    SERVICE=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl is-active rpc-translator-138.service" 2>/dev/null || echo "unknown")
    HEALTH=$(curl -s -m 5 http://$IP:9545/health 2>&1 | jq -r '.status' 2>/dev/null || echo "unknown")
    echo "  $IP: Service=$SERVICE, Health=$HEALTH"
done

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ FIX COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
