#!/bin/bash
# Setup Web3Signer keys - Copy keystore files and restart service
# Usage: ./scripts/setup-web3signer-keys.sh [keystore-directory]

set -e

KEYSTORE_DIR="${1:-./keystores}"
WEB3SIGNER_HOST="192.168.11.111"
WEB3SIGNER_DATA_DIR="/opt/web3signer/data"
WEB3SIGNER_KEYS_DIR="$WEB3SIGNER_DATA_DIR/keys"

echo "═══════════════════════════════════════════════════════════════"
echo "🔑 SETTING UP WEB3SIGNER KEYS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ ! -d "$KEYSTORE_DIR" ]; then
    echo "❌ Keystore directory not found: $KEYSTORE_DIR"
    echo ""
    echo "Usage: $0 [keystore-directory]"
    echo "Example: $0 ./keystores"
    echo ""
    echo "Or generate test keys first:"
    echo "  ./scripts/generate-test-keys.sh 3 mypassword"
    exit 1
fi

KEYSTORE_FILES=$(find "$KEYSTORE_DIR" -name "keystore-*.json" -o -name "*.json" | head -10)

if [ -z "$KEYSTORE_FILES" ]; then
    echo "❌ No keystore files found in: $KEYSTORE_DIR"
    echo "   Looking for files matching: keystore-*.json or *.json"
    exit 1
fi

echo "Found keystore files:"
echo "$KEYSTORE_FILES" | while read file; do
    echo "  - $file"
done
echo ""

# Create keys directory on Web3Signer
echo "Creating keys directory on Web3Signer..."
ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$WEB3SIGNER_HOST "mkdir -p $WEB3SIGNER_KEYS_DIR && chmod 700 $WEB3SIGNER_KEYS_DIR" 2>&1

# Copy keystore files
echo "Copying keystore files to Web3Signer..."
echo "$KEYSTORE_FILES" | while read file; do
    filename=$(basename "$file")
    echo "  Copying: $filename"
    scp -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no "$file" root@$WEB3SIGNER_HOST:$WEB3SIGNER_KEYS_DIR/ 2>&1 | grep -v "Warning: Permanently added" || true
done

# Set permissions
echo "Setting permissions..."
ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$WEB3SIGNER_HOST "chmod 600 $WEB3SIGNER_KEYS_DIR/*.json" 2>&1

# Restart Web3Signer
echo "Restarting Web3Signer service..."
ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$WEB3SIGNER_HOST "systemctl restart web3signer && sleep 3 && systemctl status web3signer --no-pager | head -8" 2>&1

# Verify keys are loaded
echo ""
echo "Verifying keys are loaded..."
sleep 2
curl -s http://$WEB3SIGNER_HOST:9000/api/v1/eth1/publicKeys 2>/dev/null | jq '.' 2>/dev/null || curl -s http://$WEB3SIGNER_HOST:9000/api/v1/eth1/publicKeys 2>/dev/null

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ WEB3SIGNER KEYS SETUP COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
