#!/bin/bash
# wg-sync-watch.sh — Watches wg0.conf for changes with debounce
# Fixed: proper debounce, error isolation, health reporting

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/wg-policy-lib.sh"

SYNC_SCRIPT="/usr/local/bin/wg-sync-policy.sh"
ENGINE_SCRIPT="/usr/local/bin/wg-policy-engine.sh"
HEALTH_INTERVAL=300  # Health check every 5 minutes
LAST_HEALTH=0

# === Validate prerequisites ===
if ! command -v inotifywait &>/dev/null; then
    log_error "inotifywait not found. Install: apt install inotify-tools"
    exit 1
fi

if [[ ! -f "$WG_CONF" ]]; then
    log_error "WireGuard config not found: $WG_CONF"
    exit 1
fi

# === Main watcher loop ===
log_info "Monitoring $WG_CONF for changes (debounce: ${DEBOUNCE_SEC}s)..."
log_info "Health check interval: ${HEALTH_INTERVAL}s"

inotifywait -m -e close_write,move,create \
    --format '%e %f' \
    "$(dirname "$WG_CONF")" 2>/dev/null | \
while read -r events filename; do

    # Only react to wg0.conf changes
    [[ "$filename" != "$(basename "$WG_CONF")" ]] && continue

    log_info "Detected change: $events $filename"

    # Debounce: wait until no more events for DEBOUNCE_SEC
    while IFS= read -r -t "$DEBOUNCE_SEC" _dummy; do
        : # Drain events within debounce window
    done

    log_info "Debounce complete, applying changes..."

    # Run sync
    if retry "$SYNC_SCRIPT"; then
        log_info "Sync successful, running engine..."

        # Run engine with retry
        if retry "$ENGINE_SCRIPT"; then
            log_info "Policy engine applied successfully"
        else
            log_error "Policy engine FAILED after retries"
        fi
    else
        log_error "Policy sync FAILED after retries"
    fi

    # Periodic health check
    local now
    now=$(date +%s)
    if (( now - LAST_HEALTH >= HEALTH_INTERVAL )); then
        LAST_HEALTH=$now
        log_info "=== Periodic Health Check ==="
        health_check || log_warn "Health check reported issues"
    fi

done
