#!/bin/bash
set -euo pipefail

ENV_FILE="/root/apprise.env"

restart_and_check_usage() {
  cat <<EOF
🛠️  Usage: restcheck_service --service NAME [--timeout N] [--interval N] [--settle-delay N]

Options:
  --service NAME      Name of the systemd service to restart and check (required).
  --timeout N         Max seconds to wait for activation (default: 30).
  --interval N        Interval in seconds between status checks (default: 2).
  --settle-delay N    Wait after activation to detect late failures (default: 5).
  --help              Show this help.

💡 Apprise URL can be provided via $ENV_FILE with:
  APPRISE_URL="https://..."

EOF
}

notify_apprise() {
  local title="$1"
  local message="$2"
  if [[ -n "${APPRISE_URL:-}" ]]; then
    apprise -t "$title" -b "$message" "$APPRISE_URL" >/dev/null 2>&1 || true
  fi
}

restcheck_service() {
  local SERVICE=""
  local TIMEOUT=30
  local INTERVAL=2
  local SETTLE_DELAY=5

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --service) SERVICE="$2"; shift 2 ;;
      --timeout) TIMEOUT="$2"; shift 2 ;;
      --interval) INTERVAL="$2"; shift 2 ;;
      --settle-delay) SETTLE_DELAY="$2"; shift 2 ;;
      --help) restart_and_check_usage; return 0 ;;
      *) echo "❌ Unknown option: $1"; restart_and_check_usage; return 1 ;;
    esac
  done

  if [[ -z "$SERVICE" ]]; then
    echo "❌ Missing --service parameter"
    restart_and_check_usage
    return 1
  fi

  if [[ -f "$ENV_FILE" ]]; then
    export $(grep -E '^APPRISE_URL=' "$ENV_FILE" | xargs)
  fi

  echo "🔁 Restarting $SERVICE..."
  if ! sudo systemctl restart "$SERVICE"; then
    echo "❌ Failed to restart $SERVICE"
    notify_apprise "❌ $SERVICE" "Restart failed on $(hostname)"
    return 2
  fi

  echo "⏳ Waiting for $SERVICE to finish activating..."
  for ((i=0; i<TIMEOUT; i+=INTERVAL)); do
    ACTIVE_STATE=$(systemctl show -p ActiveState --value "$SERVICE")
    if [[ "$ACTIVE_STATE" == "active" ]]; then
      echo "✅ $SERVICE is active after $i seconds. Waiting $SETTLE_DELAY seconds to verify stability..."
      sleep "$SETTLE_DELAY"

      FINAL_STATE=$(systemctl show -p ActiveState --value "$SERVICE")
      FINAL_RESULT=$(systemctl show -p Result --value "$SERVICE")

      if [[ "$FINAL_STATE" == "active" && "$FINAL_RESULT" == "success" ]]; then
        echo "✅ $SERVICE is stable and running."
        notify_apprise "✅ $SERVICE" "Service is stable on $(hostname)"
        return 0
      else
        echo "❌ $SERVICE became unstable (state: $FINAL_STATE, result: $FINAL_RESULT)"
        sudo systemctl status "$SERVICE"
        notify_apprise "❌ $SERVICE" "Service failed after settle delay on $(hostname)"
        return 3
      fi
    elif [[ "$ACTIVE_STATE" == "failed" ]]; then
      echo "❌ $SERVICE failed to activate."
      sudo systemctl status "$SERVICE"
      notify_apprise "❌ $SERVICE" "Service failed on $(hostname)"
      return 3
    fi
    sleep "$INTERVAL"
  done

  echo "❌ Timeout: $SERVICE did not activate within $TIMEOUT seconds."
  sudo systemctl status "$SERVICE"
  notify_apprise "❌ $SERVICE" "Service timeout on $(hostname)"
  return 3
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  restcheck_service "$@"
fi