#!/bin/bash
# Setup Health Check Cron Job
# Installs cron jobs to monitor Besu node health

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

if ! command -v pct >/dev/null 2>&1; then
    echo "Error: pct command not found. This script must be run on Proxmox host."
    exit 1
fi

LOG_DIR="$PROJECT_ROOT/logs/health-checks"
mkdir -p "$LOG_DIR"

# Create cron job script
cat > "$PROJECT_ROOT/scripts/monitoring/health-check-cron-wrapper.sh" << 'CRONSCRIPT'
#!/bin/bash
# Health check wrapper for cron
# Checks all Besu nodes and logs results

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LOG_DIR="$PROJECT_ROOT/logs/health-checks"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

for vmid in 1000 1001 1002 1003 1004 1500 1501 1502 1503 2500 2501 2502; do
    if [[ -f "$PROJECT_ROOT/scripts/health/check-node-health.sh" ]]; then
        "$PROJECT_ROOT/scripts/health/check-node-health.sh" "$vmid" >> "$LOG_DIR/health-$vmid-$TIMESTAMP.log" 2>&1
    fi
done

# Cleanup old logs (keep 7 days)
find "$LOG_DIR" -name "health-*.log" -mtime +7 -delete 2>/dev/null || true
CRONSCRIPT

chmod +x "$PROJECT_ROOT/scripts/monitoring/health-check-cron-wrapper.sh"

# Add to crontab (every 5 minutes)
CRON_JOB="*/5 * * * * $PROJECT_ROOT/scripts/monitoring/health-check-cron-wrapper.sh"

if crontab -l 2>/dev/null | grep -q "health-check-cron-wrapper.sh"; then
    echo "Cron job already exists"
else
    (crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
    echo "✓ Health check cron job installed (runs every 5 minutes)"
    echo "  Logs: $LOG_DIR/"
    echo "  To remove: crontab -e (then delete the line)"
fi
