#!/bin/bash

# === Configuration ===
LOGFILE="/tmp/dispatcher.log"
BACKUP="/tmp/dispatcher.log.1"
MAXSIZE=$((1024 * 1024))  # 1 MB
VPN_IFACE="nl"
GATEWAY="192.168.178.1"
LOCAL_IFACE="wlp4s0f0"
ROUTE1="185.183.34.149"
ROUTE2="192.168.178.0/24"

# === Log Rotation ===
if [ -f "$LOGFILE" ] && [ "$(stat -c%s "$LOGFILE")" -ge "$MAXSIZE" ]; then
  echo "[$(date)] Log file exceeded 1MB, rotating..." >> "$LOGFILE"
  mv "$LOGFILE" "$BACKUP"
  touch "$LOGFILE"
fi

# === Logging Setup ===
exec >> "$LOGFILE" 2>&1
echo "[$(date)] Running dispatcher for $1 with status $2"

IFACE="$1"
STATUS="$2"

log_and_run() {
  echo "[$(date)] Executing: $*"
  if ! output=$("$@" 2>&1); then
    echo "[$(date)] ERROR: Command failed: $*"
    echo "[$(date)] Output: $output"
  else
    echo "[$(date)] Success: $*"
  fi
}

# === VPN Routing Logic ===
if [ "$IFACE" = "$VPN_IFACE" ]; then
  case "$STATUS" in
    up)
      echo "[$(date)] VPN interface is up. Preparing routes..."

      # === Wait for local interface and gateway ===
      echo "[$(date)] Waiting for $LOCAL_IFACE (state UP) and gateway $GATEWAY (reachable)..."
      until ip link show "$LOCAL_IFACE" | grep -q "state UP" && ip route get "$GATEWAY" &>/dev/null; do
        echo "[$(date)] Waiting for $LOCAL_IFACE and $GATEWAY..."
        sleep 1
      done
      echo "[$(date)] Local interface and gateway are ready."
      # === End Wait ===

      # === APPLY ROUTES (Corrected Order) ===
      
      # 1. Add the route for the local network FIRST
      log_and_run /sbin/ip route replace "$ROUTE2" dev "$LOCAL_IFACE"
      
      # 2. Add the route to the VPN endpoint via the gateway SECOND
      log_and_run /sbin/ip route replace "$ROUTE1" via "$GATEWAY" dev "$LOCAL_IFACE"
      
      # === END APPLY ROUTES ===

      # Log interface and WireGuard status
      echo "[$(date)] --- ip addr show $VPN_IFACE ---"
      ip addr show "$VPN_IFACE"
      echo "[$(date)] --- wg show $VPN_IFACE ---"
      wg show "$VPN_IFACE"

      ;;

    down)
      echo "[$(date)] VPN interface is down. Verifying before removing routes..."

      # Log interface and WireGuard status
      echo "[$(date)] --- ip addr show $VPN_IFACE ---"
      ip addr show "$VPN_IFACE"
      echo "[$(date)] --- wg show $VPN_IFACE ---"
      wg show "$VPN_IFACE"

      # Delay and confirm interface is still down
      sleep 5
      if ip link show "$VPN_IFACE" | grep -q "state UP"; then
        echo "[$(date)] VPN interface is still up. Skipping route removal."
      else
        echo "[$(date)] Confirmed VPN is down. Removing routes..."
        # It's good practice to remove them in reverse order, too.
        log_and_run /sbin/ip route del "$ROUTE1" via "$GATEWAY" dev "$LOCAL_IFACE"
        log_and_run /sbin/ip route del "$ROUTE2" dev "$LOCAL_IFACE"
      fi
      ;;
  esac
fi
