#!/bin/bash
set -euo pipefail

# ─── Load Shared Functions ───
source /opt/scripts_local/shared_functions.sh

# ─── Configuration ───
MY_SCRIPT="tailscale_net_update"
SCRIPT_PATH="/opt/scripts_local/${MY_SCRIPT}.sh"
SERVICE_PATH="/etc/systemd/system/${MY_SCRIPT}.service"
TEMPLATE_SCRIPT="/myshares/shared/opt/scripts_local/${MY_SCRIPT}.sh"
TEMPLATE_SERVICE="/myshares/shared/etc/systemd/system/${MY_SCRIPT}.service"
MARKER_DIR="/etc/setup-markers"
MARKER="${MARKER_DIR}/${MY_SCRIPT}_configured"

# ─── Cleanup Old ip_route_add_delayed Service ───
OLD_SCRIPT_NAME="ip_route_add_delayed"
OLD_SERVICE_PATH="/etc/systemd/system/${OLD_SCRIPT_NAME}.service"
OLD_SCRIPT_PATH="/opt/scripts_local/${OLD_SCRIPT_NAME}.sh"

if [[ -f "$OLD_SERVICE_PATH" || -f "$OLD_SCRIPT_PATH" ]]; then
  log "🧹 Detected old script/service: $OLD_SCRIPT_NAME"

  if systemctl list-units --full -all | grep -q "${OLD_SCRIPT_NAME}.service"; then
    if systemctl is-active --quiet "${OLD_SCRIPT_NAME}.service"; then
      log "🛑 Stopping old service: ${OLD_SCRIPT_NAME}.service"
      systemctl stop "${OLD_SCRIPT_NAME}.service"
    fi

    log "🚫 Disabling old service: ${OLD_SCRIPT_NAME}.service"
    systemctl disable "${OLD_SCRIPT_NAME}.service"
  fi

  log "🗑️ Optionally removing old script and service files"
  rm -f "$OLD_SCRIPT_PATH" "$OLD_SERVICE_PATH"
  systemctl daemon-reload
  log "✅ Old service cleaned up: $OLD_SCRIPT_NAME"
fi


FORCE=false

# ─── Logging Function ───
log() {
  echo "[$(date +'%F %T')] $*"
}

# ─── Argument Parsing ───
for arg in "$@"; do
  case "$arg" in
    --force)
      FORCE=true
      log "⚠️  Force mode enabled — setup will re-run even if already marked as completed"
      ;;
    --help|-h)
      echo "Usage: $0 [--force]"
      echo "  --force   Re-run setup even if already marked as completed"
      exit 0
      ;;
    *)
      log "❌ Unknown option: $arg"
      echo "Run with --help for usage."
      exit 1
      ;;
  esac
done

# ─── Remove Legacy Cron Job (root crontab) ───
log "🧹 Checking for legacy cron job in root's crontab..."

TMP_CRON=$(mktemp)
ROOT_CRON=$(crontab -u root -l 2>/dev/null || true)
MATCHING_LINES=$(echo "$ROOT_CRON" | grep "@reboot" | grep "ip rule" | grep "192.168.10.0/24" || true)

if [[ -n "$MATCHING_LINES" ]]; then
  echo "$ROOT_CRON" | grep -v "ip rule" | grep -v "192.168.10.0/24" | grep -v "@reboot" > "$TMP_CRON"
  crontab -u root "$TMP_CRON"
  log "🧽 Removed legacy cron job(s) from root's crontab."
  logger -t "$MY_SCRIPT" "Removed legacy cron job(s) from root's crontab containing '@reboot', 'ip rule', and '192.168.10.0/24'"
else
  log "✅ No legacy cron job found in root's crontab."
fi
rm -f "$TMP_CRON"

# ─── Remove Legacy Cron Jobs in /etc/cron.d ───
log "🔍 Scanning /etc/cron.d for legacy cron jobs..."

for cronfile in /etc/cron.d/*; do
  [[ -f "$cronfile" ]] || continue
  if grep -q "@reboot" "$cronfile" && grep -q "ip rule" "$cronfile" && grep -q "192.168.10.0/24" "$cronfile"; then
    cp "$cronfile" "$cronfile.bak"
    grep -v "@reboot" "$cronfile" | grep -v "ip rule" | grep -v "192.168.10.0/24" > "${cronfile}.tmp"
    mv "${cronfile}.tmp" "$cronfile"
    log "🧽 Removed legacy cron line from: $cronfile"
    logger -t "$MY_SCRIPT" "Removed legacy cron line from $cronfile"
  fi
done

# ─── Remove Legacy Cron Job in /etc/crontab ───
CRONTAB_FILE="/etc/crontab"
if [[ -f "$CRONTAB_FILE" ]] && grep -q "@reboot" "$CRONTAB_FILE" && grep -q "ip rule" "$CRONTAB_FILE" && grep -q "192.168.10.0/24" "$CRONTAB_FILE"; then
  cp "$CRONTAB_FILE" "$CRONTAB_FILE.bak"
  grep -v "@reboot" "$CRONTAB_FILE" | grep -v "ip rule" | grep -v "192.168.10.0/24" > "${CRONTAB_FILE}.tmp"
  mv "${CRONTAB_FILE}.tmp" "$CRONTAB_FILE"
  log "🧽 Removed legacy cron line from: $CRONTAB_FILE"
  logger -t "$MY_SCRIPT" "Removed legacy cron line from $CRONTAB_FILE"
else
  log "✅ No legacy cron job found in /etc/crontab."
fi

# ─── Marker Check ───
if [[ -f "$MARKER" && "$FORCE" = false ]]; then
  log "⏩ Skipping setup: marker file already exists → $MARKER"
  log "ℹ️  Use '--force' to re-run setup even if already configured."
  exit 0
fi

# ─── Marker Directory ───
mkdir -p "$MARKER_DIR"

# ─── Install Script ───
log "📥 Installing script: $MY_SCRIPT"
download_template "$TEMPLATE_SCRIPT" "$SCRIPT_PATH"
chmod +x "$SCRIPT_PATH"

# ─── Install Systemd Service ───
log "📥 Installing systemd service for: $MY_SCRIPT"
download_template "$TEMPLATE_SERVICE" "$SERVICE_PATH"
chmod 600 "$SERVICE_PATH"

# ─── Reload and Enable Service ───
log "🔁 Reloading systemd daemon"
systemctl daemon-reload

if systemctl is-active --quiet "${MY_SCRIPT}.service"; then
  log "🛑 Stopping existing ${MY_SCRIPT}.service"
  systemctl stop "${MY_SCRIPT}.service"
fi

log "✅ Enabling and starting service: $MY_SCRIPT"
systemctl enable "${MY_SCRIPT}.service"
systemctl restart "${MY_SCRIPT}.service"

# ─── Create Marker ───
touch "$MARKER"
log "📝 Setup marker created: $MARKER"

# ─── Final Confirmation ───
log "✅ Setup completed successfully for $MY_SCRIPT"