#!/bin/bash
# Deploy corrected allowlist files to all Proxmox containers
# Usage: bash besu-deploy-allowlist.sh <static-nodes.json> <permissions-nodes.toml> [proxmox-host]

set -euo pipefail

PROXMOX_HOST="${3:-192.168.11.10}"
STATIC_NODES_FILE="${1:-static-nodes.json}"
PERMISSIONS_TOML_FILE="${2:-permissions-nodes.toml}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [[ ! -f "$STATIC_NODES_FILE" ]] || [[ ! -f "$PERMISSIONS_TOML_FILE" ]]; then
    echo "ERROR: Files not found:" >&2
    [[ ! -f "$STATIC_NODES_FILE" ]] && echo "  - $STATIC_NODES_FILE" >&2
    [[ ! -f "$PERMISSIONS_TOML_FILE" ]] && echo "  - $PERMISSIONS_TOML_FILE" >&2
    exit 1
fi

# Validate files first
echo "Validating files before deployment..."
if ! bash "${SCRIPT_DIR}/besu-validate-allowlist.sh" "$STATIC_NODES_FILE" "$PERMISSIONS_TOML_FILE"; then
    echo "ERROR: Validation failed. Fix files before deploying." >&2
    exit 1
fi

echo ""
echo "Deploying to Proxmox host: $PROXMOX_HOST"

# Copy files to host
scp -o StrictHostKeyChecking=accept-new \
    "$STATIC_NODES_FILE" \
    "$PERMISSIONS_TOML_FILE" \
    "root@${PROXMOX_HOST}:/tmp/"

# Deploy to all containers
for vmid in 1000 1001 1002 1003 1004 1500 1501 1502 1503 2500 2501 2502; do
    echo "Deploying to container $vmid..."
    
    ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" << DEPLOY_SCRIPT
if ! pct status $vmid 2>/dev/null | grep -q running; then
    echo "  Container $vmid not running, skipping"
    exit 0
fi

pct push $vmid /tmp/$(basename $STATIC_NODES_FILE) /etc/besu/static-nodes.json
pct push $vmid /tmp/$(basename $PERMISSIONS_TOML_FILE) /etc/besu/permissions-nodes.toml
pct exec $vmid -- chown besu:besu /etc/besu/static-nodes.json /etc/besu/permissions-nodes.toml

if pct exec $vmid -- test -f /etc/besu/static-nodes.json && \
   pct exec $vmid -- test -f /etc/besu/permissions-nodes.toml; then
    echo "  ✓ Container $vmid: Files deployed"
else
    echo "  ✗ Container $vmid: Deployment failed"
fi
DEPLOY_SCRIPT

done

# Cleanup
ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
    "rm -f /tmp/$(basename $STATIC_NODES_FILE) /tmp/$(basename $PERMISSIONS_TOML_FILE)"

echo ""
echo "✓ Deployment complete"
echo ""
echo "Next steps:"
echo "1. Restart Besu services on all containers"
echo "2. Run verification: bash ${SCRIPT_DIR}/besu-verify-peers.sh <rpc-url>"
