#!/bin/bash
# Generate Besu allowlist files from collected enodes
# Usage: bash besu-generate-allowlist.sh <collected-enodes.txt> [validator-ips...]

set -euo pipefail

COLLECTED_FILE="${1:-}"
OUTPUT_DIR="${OUTPUT_DIR:-.}"

if [[ -z "$COLLECTED_FILE" ]] || [[ ! -f "$COLLECTED_FILE" ]]; then
    echo "Usage: $0 <collected-enodes.txt> [validator-ip1] [validator-ip2] ..." >&2
    echo "Example: $0 collected-enodes.txt 192.168.11.13 192.168.11.14 192.168.11.15 192.168.11.16 192.168.11.18" >&2
    exit 1
fi

shift || true
VALIDATOR_IPS=("$@")

# If no validator IPs provided, use first 5 entries
if [[ ${#VALIDATOR_IPS[@]} -eq 0 ]]; then
    VALIDATOR_IPS=($(head -5 "$COLLECTED_FILE" | cut -d'|' -f1))
fi

GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }

log_info "Generating allowlist files..."

python3 << PYEOF
import json
import sys

collected_file = '$COLLECTED_FILE'
validator_ips = ${VALIDATOR_IPS[@]}
output_dir = '$OUTPUT_DIR'

# Read collected enodes
enodes_all = []
enodes_validators = []

with open(collected_file, 'r') as f:
    for line in f:
        line = line.strip()
        if not line or '|' not in line:
            continue
        parts = line.split('|')
        if len(parts) >= 2:
            ip = parts[0]
            enode = parts[1]
            enodes_all.append(enode)
            if ip in validator_ips:
                enodes_validators.append(enode)

# Sort for determinism
enodes_all.sort()
enodes_validators.sort()

# Generate static-nodes.json (validators only)
static_nodes_file = f'{output_dir}/static-nodes.json'
with open(static_nodes_file, 'w') as f:
    json.dump(enodes_validators, f, indent=2)

print(f"Generated {static_nodes_file} with {len(enodes_validators)} validators")

# Generate permissions-nodes.toml (all nodes)
permissions_file = f'{output_dir}/permissions-nodes.toml'
toml_content = f"""# Node Permissioning Configuration
# Lists nodes that are allowed to connect to this node
# Generated: {__import__('datetime').datetime.now().isoformat()}
# Total nodes: {len(enodes_all)}

nodes-allowlist=[
"""

for enode in enodes_all:
    toml_content += f'  "{enode}",\n'

toml_content = toml_content.rstrip(',\n') + '\n]'

with open(permissions_file, 'w') as f:
    f.write(toml_content)

print(f"Generated {permissions_file} with {len(enodes_all)} nodes")
PYEOF

log_success "Files generated in: $OUTPUT_DIR"
log_info "  - static-nodes.json (validators)"
log_info "  - permissions-nodes.toml (all nodes)"
