#!/bin/bash
# Complete setup script - Generates keys and configures allowlist
# Usage: ./scripts/setup-complete.sh [key-count] [password]

set -e

KEY_COUNT="${1:-3}"
PASSWORD="${2:-changeme}"

echo "═══════════════════════════════════════════════════════════════"
echo "🚀 COMPLETE SETUP - WEB3SIGNER KEYS AND ALLOWLIST"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "This script will:"
echo "  1. Generate test keystore files"
echo "  2. Copy keys to Web3Signer"
echo "  3. Get public keys (addresses)"
echo "  4. Configure wallet allowlist on all translators"
echo ""

# Generate keys
echo "Step 1: Generating test keys..."
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

cd "$TEMP_DIR"
if command -v node &> /dev/null; then
    # Use Node.js if available
    node <<NODEJS
const crypto = require('crypto');
const fs = require('fs');

function generateKeystore(privateKey, password) {
  const uuid = crypto.randomUUID();
  const salt = crypto.randomBytes(32);
  const iv = crypto.randomBytes(16);
  
  const kdfparams = { dklen: 32, salt: salt.toString('hex'), n: 16384, r: 8, p: 1 };
  const derivedKey = crypto.scryptSync(Buffer.from(password), salt, 32, {
    cost: kdfparams.n, blockSize: kdfparams.r, parallelization: kdfparams.p, maxmem: 256 * 1024 * 1024
  });
  
  const cipher = crypto.createCipheriv('aes-128-ctr', derivedKey.slice(0, 16), iv);
  const ciphertext = Buffer.concat([cipher.update(privateKey), cipher.final()]);
  
  const mac = crypto.createHmac('sha256', derivedKey.slice(16, 32))
    .update(Buffer.concat([iv, ciphertext])).digest();
  
  const address = '0x' + crypto.createHash('sha3-256')
    .update(privateKey).digest('hex').slice(-40);
  
  return { keystore: {
    version: 3, id: uuid, address: address,
    crypto: {
      ciphertext: ciphertext.toString('hex'),
      cipherparams: { iv: iv.toString('hex') },
      cipher: 'aes-128-ctr', kdf: 'scrypt', kdfparams: kdfparams,
      mac: mac.toString('hex')
    }
  }, address: address };
}

const count = parseInt('$KEY_COUNT');
const password = '$PASSWORD';

for (let i = 0; i < count; i++) {
  const privateKey = crypto.randomBytes(32);
  const { keystore, address } = generateKeystore(privateKey, password);
  const filename = \`keystore-test-\${i + 1}.json\`;
  fs.writeFileSync(filename, JSON.stringify(keystore, null, 2));
  console.log(\`Generated: \${filename} -> \${address}\`);
}
NODEJS
else
    echo "⚠️  Node.js not available - skipping key generation"
    echo "   Install Node.js or provide keystore files manually"
    exit 1
fi

# Setup Web3Signer keys
echo ""
echo "Step 2: Setting up Web3Signer keys..."
cd /home/intlc/projects/proxmox/rpc-translator-138
./scripts/setup-web3signer-keys.sh "$TEMP_DIR" 2>&1 | tail -20

# Get public keys
echo ""
echo "Step 3: Getting public keys..."
sleep 3
PUBLIC_KEYS=$(curl -s http://192.168.11.111:9000/api/v1/eth1/publicKeys 2>/dev/null || echo "[]")

if [ "$PUBLIC_KEYS" != "[]" ] && [ -n "$PUBLIC_KEYS" ]; then
    ADDRESSES=$(echo "$PUBLIC_KEYS" | jq -r '.[]' 2>/dev/null | tr '\n' ',' | sed 's/,$//')
    
    if [ -n "$ADDRESSES" ]; then
        echo "Found addresses: $ADDRESSES"
        echo ""
        echo "Step 4: Configuring wallet allowlist..."
        ./scripts/configure-wallet-allowlist.sh "$ADDRESSES" 2>&1 | tail -15
    else
        echo "⚠️  Could not parse addresses from Web3Signer"
    fi
else
    echo "⚠️  No keys found in Web3Signer"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ SETUP COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
