#!/bin/bash
# Generate keys and prepare for loading to Web3Signer
# Usage: ./scripts/generate-and-load-keys.sh [count] [password]

set -e

COUNT="${1:-3}"
PASSWORD="${2:-TestWallet123!}"
OUTPUT_DIR="/tmp/web3signer-keys"

echo "═══════════════════════════════════════════════════════════════"
echo "🔑 GENERATING KEYSTORE FILES"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Count: $COUNT"
echo "Output: $OUTPUT_DIR"
echo ""

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Check for Node.js (try node or nodejs)
NODE_CMD=""
if command -v node &> /dev/null; then
    NODE_CMD="node"
elif command -v nodejs &> /dev/null; then
    NODE_CMD="nodejs"
elif [ -f "/home/intlc/.nvm/nvm.sh" ]; then
    # Try loading nvm
    source /home/intlc/.nvm/nvm.sh 2>/dev/null
    if command -v node &> /dev/null; then
        NODE_CMD="node"
    fi
fi

if [ -z "$NODE_CMD" ]; then
    # Try pnpm/npx if we're in a Node.js project
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
    
    if [ -f "$PROJECT_DIR/package.json" ]; then
        if command -v pnpm &> /dev/null; then
            cd "$PROJECT_DIR"
            NODE_CMD="pnpm exec node"
            echo "ℹ️  Using pnpm exec node (from project directory)"
        elif [ -f "$PROJECT_DIR/node_modules/.bin/node" ]; then
            NODE_CMD="$PROJECT_DIR/node_modules/.bin/node"
            echo "ℹ️  Using node from node_modules"
        elif command -v npx &> /dev/null; then
            NODE_CMD="npx --yes node"
            echo "ℹ️  Using npx node"
        fi
    fi
fi

if [ -z "$NODE_CMD" ]; then
    echo "❌ Node.js is required but not found"
    echo ""
    echo "Please install Node.js. Quick install:"
    echo "  curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -"
    echo "  sudo apt-get install -y nodejs"
    echo ""
    echo "Or see NODEJS_REQUIRED.md for more options"
    exit 1
fi

# Generate keys
cd "$OUTPUT_DIR"
$NODE_CMD <<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('$COUNT');
const password = '$PASSWORD';

console.log('Generating keystore files...');
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

echo ""
echo "✅ Keys generated in: $OUTPUT_DIR"
echo ""
echo "Files:"
ls -lh "$OUTPUT_DIR"/keystore-*.json

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "📋 NEXT STEPS"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "1. Copy keys to Proxmox host:"
echo "   scp $OUTPUT_DIR/keystore-*.json root@ml110:/tmp/web3signer-keys/"
echo ""
echo "2. Load keys into Web3Signer container:"
echo "   ssh root@ml110 'bash -s' < /home/intlc/projects/proxmox/rpc-translator-138/scripts/load-keys-complete.sh"
echo ""
echo "Or manually:"
echo "   ssh root@ml110"
echo "   pct push 107 /tmp/web3signer-keys/keystore-test-1.json /opt/web3signer/data/keys/"
echo "   pct push 107 /tmp/web3signer-keys/keystore-test-2.json /opt/web3signer/data/keys/"
echo "   pct push 107 /tmp/web3signer-keys/keystore-test-3.json /opt/web3signer/data/keys/"
echo "   pct exec 107 -- chmod 644 /opt/web3signer/data/keys/*.json"
echo "   pct exec 107 -- systemctl restart web3signer"
echo ""
