#!/bin/bash

# Parameters and constants
MARKER_NAME="tailscale-route-fix"
SCRIPT_DIR="/myshares/scripts"
SYSTEMD_UNIT="tailscale-routing-fix.service"
SYSTEMD_TARGET_PATH="/etc/systemd/system/${SYSTEMD_UNIT}"

# Handle --force flag
FORCE=false
for arg in "$@"; do
  [[ "$arg" == "--force" ]] && FORCE=true
done

# 🛡️ Root check
if [[ "$EUID" -ne 0 ]]; then
  echo "❌ This script must be run as root."
  exit 1
fi

# 🧠 Load shared functions
if [[ -f "$SCRIPT_DIR/shared_functions.sh" ]]; then
  source "$SCRIPT_DIR/shared_functions.sh"
else
  echo "❌ Cannot find shared_functions.sh in $SCRIPT_DIR"
  exit 1
fi

# 🧭 Marker check
setup_marker check "$MARKER_NAME" "$FORCE"

# 🧽 Clean old crontab line(s) for current user
echo "🔍 Checking crontab entries for matching 'ip rule' + '192.168.10.0/24'..."
if crontab -l 2>/dev/null | grep -qE 'ip rule' && crontab -l | grep -q '192.168.10.0/24'; then
  TMP_CRON="/tmp/cleaned_cron_$$"
  crontab -l | grep -vE 'ip rule.*192\.168\.10\.0/24|192\.168\.10\.0/24.*ip rule' > "$TMP_CRON"
  crontab "$TMP_CRON"
  rm -f "$TMP_CRON"
  echo "✅ Crontab entry removed."
else
  echo "ℹ️ No matching crontab entry found."
fi

# 🧽 Check /etc/cron.d/ for matching lines
echo "🔍 Scanning /etc/cron.d/ for matching tasks..."
FOUND_FILES=$(grep -rlE 'ip rule.*192\.168\.10\.0/24|192\.168\.10\.0/24.*ip rule' /etc/cron.d/ 2>/dev/null || true)

if [[ -n "$FOUND_FILES" ]]; then
  echo "⚠️ Matching cron job(s) found in:"
  echo "$FOUND_FILES"
  echo "🧹 Deleting..."
  while read -r file; do
    echo "🗑️ Removing $file"
    rm -f "$file"
  done <<< "$FOUND_FILES"
else
  echo "✅ No cron jobs found in /etc/cron.d/ needing removal."
fi

# 🔁 Rsync the service file
echo "📦 Deploying $SYSTEMD_UNIT..."
rsync -av "$SCRIPT_DIR/shared/etc/systemd/system/$SYSTEMD_UNIT" "$SYSTEMD_TARGET_PATH"

# 🔧 Enable and start the service
echo "🚀 Enabling and starting the service..."
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable --now "$SYSTEMD_UNIT"

# 🏁 Create setup marker
setup_marker create "$MARKER_NAME"
