#!/bin/bash
# Complete key loading script - Run from Proxmox host (ml110)
# Usage: ssh root@ml110 'bash -s' < scripts/load-keys-complete.sh

set -e

echo "═══════════════════════════════════════════════════════════════"
echo "🔑 LOADING WEB3SIGNER KEYS - COMPLETE PROCESS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Step 1: Create keys directory
echo "Step 1: Creating keys directory..."
pct exec 107 -- mkdir -p /opt/web3signer/data/keys

# Step 2: Check if keys exist in /tmp/web3signer-keys
echo ""
echo "Step 2: Looking for keystore files..."
if [ -d "/tmp/web3signer-keys" ] && [ -n "$(ls -A /tmp/web3signer-keys/keystore-*.json 2>/dev/null)" ]; then
    echo "Found keystore files in /tmp/web3signer-keys"
    KEY_DIR="/tmp/web3signer-keys"
else
    echo "⚠️  No keystore files found in /tmp/web3signer-keys"
    echo "   Please copy keystore files to /tmp/web3signer-keys/ on the Proxmox host first"
    exit 1
fi

# Step 3: Copy keys to Web3Signer
echo ""
echo "Step 3: Copying keys to Web3Signer container..."
for file in "$KEY_DIR"/keystore-*.json; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        pct push 107 "$file" "/opt/web3signer/data/keys/$filename"
        echo "  ✅ Copied: $filename"
    fi
done

# Step 4: Set permissions
echo ""
echo "Step 4: Setting permissions..."
pct exec 107 -- bash -c "chmod 644 /opt/web3signer/data/keys/*.json 2>/dev/null || echo 'Note: Setting permissions on individual files'"
pct exec 107 -- bash -c "for f in /opt/web3signer/data/keys/*.json; do [ -f \"\$f\" ] && chmod 644 \"\$f\"; done"
pct exec 107 -- ls -lh /opt/web3signer/data/keys/

# Step 5: Restart Web3Signer
echo ""
echo "Step 5: Restarting Web3Signer..."
pct exec 107 -- systemctl restart web3signer
sleep 5

# Step 6: Verify keys loaded
echo ""
echo "Step 6: Verifying keys are loaded..."
KEYS=$(pct exec 107 -- curl -s http://localhost:9000/api/v1/eth1/publicKeys 2>/dev/null || echo "[]")

if [ "$KEYS" != "[]" ] && [ -n "$KEYS" ]; then
    KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
    if [ "$KEY_COUNT" -gt 0 ]; then
        echo "  ✅ SUCCESS: $KEY_COUNT key(s) loaded!"
        echo ""
        echo "Loaded addresses:"
        echo "$KEYS" | jq -r '.[]' | while read addr; do
            echo "  - $addr"
        done
        
        # Save addresses for allowlist configuration
        ADDRESSES=$(echo "$KEYS" | jq -r '.[]' | tr '\n' ',' | sed 's/,$//')
        echo "$ADDRESSES" > /tmp/web3signer-addresses.txt
        echo ""
        echo "Addresses saved to /tmp/web3signer-addresses.txt"
    else
        echo "  ⚠️  Keys endpoint returned empty array"
    fi
else
    echo "  ⚠️  No keys loaded yet or Web3Signer not responding"
    echo ""
    echo "Checking Web3Signer logs..."
    pct exec 107 -- journalctl -u web3signer.service -n 20 --no-pager
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ KEY LOADING PROCESS COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
