#!/bin/bash
# Generate test Ethereum keystore files for Web3Signer
# Usage: ./scripts/generate-test-keys.sh [count] [password]
# Example: ./scripts/generate-test-keys.sh 3 mypassword

set -e

COUNT="${1:-1}"
PASSWORD="${2:-changeme}"

echo "═══════════════════════════════════════════════════════════════"
echo "🔑 GENERATING TEST KEYSTORE FILES"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Count: $COUNT"
echo "Password: (hidden)"
echo ""
echo "⚠️  WARNING: These are TEST keys only!"
echo "   Do NOT use in production without proper security measures."
echo ""

# Check if node is available
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is required but not installed"
    echo "   Install Node.js to generate keystore files"
    exit 1
fi

# Create temp directory
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

echo "Generating keystore files..."

# Generate keystore files using Node.js
cat > "$TEMP_DIR/generate-keystore.js" <<'NODEJS'
const crypto = require('crypto');
const fs = require('fs');
const { scrypt, randomBytes } = crypto;

function generateKeystore(privateKey, password, uuid, salt, iv) {
  const kdf = 'scrypt';
  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();

  return {
    version: 3,
    id: uuid,
    address: '0x' + crypto.createHash('sha3-256')
      .update(privateKey)
      .digest('hex')
      .slice(-40),
    crypto: {
      ciphertext: ciphertext.toString('hex'),
      cipherparams: {
        iv: iv.toString('hex')
      },
      cipher: 'aes-128-ctr',
      kdf: kdf,
      kdfparams: kdfparams,
      mac: mac.toString('hex')
    }
  };
}

const count = parseInt(process.argv[2] || '1');
const password = process.argv[3] || 'changeme';
const outputDir = process.argv[4] || './';

for (let i = 0; i < count; i++) {
  const privateKey = randomBytes(32);
  const uuid = require('crypto').randomUUID();
  const salt = randomBytes(32);
  const iv = randomBytes(16);
  
  const keystore = generateKeystore(privateKey, password, uuid, salt, iv);
  
  const filename = `keystore-test-${i + 1}.json`;
  const filepath = `${outputDir}/${filename}`;
  
  fs.writeFileSync(filepath, JSON.stringify(keystore, null, 2));
  console.log(`Generated: ${filename} (address: ${keystore.address})`);
}
NODEJS

cd "$TEMP_DIR"
node generate-keystore.js "$COUNT" "$PASSWORD" "$TEMP_DIR" 2>&1

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ KEYSTORE FILES GENERATED"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Files generated in: $TEMP_DIR"
echo ""
echo "Next steps:"
echo "1. Review the generated keystore files"
echo "2. Copy them to Web3Signer data directory:"
echo "   scp $TEMP_DIR/keystore-*.json root@192.168.11.111:/opt/web3signer/data/keys/"
echo "3. Restart Web3Signer:"
echo "   ssh root@192.168.11.111 'systemctl restart web3signer'"
echo ""
echo "⚠️  Remember to:"
echo "   - Change the password for production use"
echo "   - Secure the private keys"
echo "   - Back up keys safely"
echo ""
echo "Files will be cleaned up when script exits."
echo "Copy them now if you need them."
