#!/bin/bash
set -euo pipefail

if [[ "$EUID" -ne 0 ]]; then
  echo "❌ This script must be run as root. Please use sudo."
  exit 1
fi

# Optional argument for filtering by name
FILTER_NAME="${1:-}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONF_FILE="$SCRIPT_DIR/sqlite_maint.conf"
SQLITE_BIN="sqlite3"

# Wait for container to fully stop
wait_for_container_stop() {
  local container="$1"
  local timeout=60
  local elapsed=0
  while [[ $elapsed -lt $timeout ]]; do
    if ! docker inspect -f '{{.State.Running}}' "$container" 2>/dev/null | grep -q true; then
      echo "✅ Container $container has stopped."
      return 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
  done
  echo "⚠️  Timeout waiting for container $container to stop."
  return 1
}

# Rotate backups: keep only the most recent N
rotate_backups() {
  local dir="$1"
  local base="$(basename "$2")"
  local limit="$3"
  ls -1t "$dir/$base".bak.* 2>/dev/null | tail -n +"$((limit+1))" | xargs -r rm -f
}

# Notify Kuma
notify_kuma() {
  local kuma_id="$1"
  local status="$2"
  [[ -z "$kuma_id" ]] && return
  local url="https://uptime.noxs.me/api/push/$kuma_id?status=$status"
  curl -fsSL --max-time 10 "$url" >/dev/null && \
    echo "📡 Kuma notified: $status" || \
    echo "⚠️  Failed to notify Kuma ($status)"
}

if [[ ! -f "$CONF_FILE" ]]; then
  echo "❌ Config file not found: $CONF_FILE"
  exit 1
fi

mapfile -t lines < "$CONF_FILE"
for line in "${lines[@]}"; do
  [[ -z "$line" || "${line:0:1}" == "#" ]] && continue
  IFS="|" read -r host name db_path backup_dir max_backups kuma_id no_restart no_backup service_name <<< "$line"

  if [[ -n "$FILTER_NAME" && "$FILTER_NAME" != "$name" ]]; then
    continue
  fi

  if [[ "$host" != "localhost" && "$host" != "$(hostname)" ]]; then
    echo "🔁 Skipping $name: not for this host ($host)"
    continue
  fi

  echo "🚀 Processing: $name"

  if [[ ! -x "$(command -v "$SQLITE_BIN")" ]]; then
    echo "⚠️  sqlite3 not found. Attempting to install..."
    if command -v apt-get &>/dev/null; then
      apt-get update && apt-get install -y sqlite3
    elif command -v apk &>/dev/null; then
      apk add --no-cache sqlite
    else
      echo "❌ sqlite3 installation failed"
      # notify_kuma "$kuma_id" "down"
      continue
    fi
  fi

  if [[ ! -f "$db_path" ]]; then
    echo "❌ Database file not found: $db_path"
    # notify_kuma "$kuma_id" "down"
    continue
  fi

  if [[ "$no_restart" != "true" ]]; then
    if [[ -n "${service_name:-}" ]]; then
      echo "🛑 Stopping systemd service: $service_name..."
      systemctl stop "$service_name"
      echo "⏳ Waiting 30 seconds..."
      sleep 30
    else
      echo "⏳ Stopping container $name..."
      container_state="$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null || echo "notfound")"
      if [[ "$container_state" == "true" ]]; then
        docker stop -t 60 "$name" || docker kill "$name"
        wait_for_container_stop "$name"
      else
        echo "ℹ️  No container $name running"
      fi
    fi
  fi

  if [[ "$no_backup" != "true" ]]; then
    mkdir -p "$backup_dir"
    BACKUP_NAME="$(basename "$db_path").bak.$(date +%Y%m%d_%H%M%S)"
    BACKUP_FILE="$backup_dir/$BACKUP_NAME"
    cp "$db_path" "$BACKUP_FILE"
    echo "✅ Backup created: $BACKUP_FILE"

    if [[ "$max_backups" =~ ^[0-9]+$ && "$max_backups" -gt 0 ]]; then
      rotate_backups "$backup_dir" "$db_path" "$max_backups"
    fi
  else
    echo "⏭️  Backup skipped due to no_backup=true"
  fi

  echo "🔎 Checking DB integrity..."
  if ! $SQLITE_BIN "$db_path" "PRAGMA integrity_check;" | grep -q ok; then
    echo "❌ Integrity check failed for $db_path"
    # notify_kuma "$kuma_id" "down"
    if [[ "$no_restart" != "true" ]]; then
      if [[ -n "${service_name:-}" ]]; then
        systemctl start "$service_name"
      else
        docker start "$name" || echo "❌ Failed to restart container $name"
      fi
    fi
    continue
  fi
  echo "✅ Integrity check passed"

  echo "🧹 Running VACUUM..."
  $SQLITE_BIN "$db_path" "VACUUM;"

  echo "⚡ Running PRAGMA optimize..."
  $SQLITE_BIN "$db_path" "PRAGMA optimize;"

  if [[ "$no_restart" != "true" ]]; then
    if [[ -n "${service_name:-}" ]]; then
      echo "🚀 Starting systemd service $service_name..."
      systemctl start "$service_name"
    else
      echo "🚀 Starting container $name..."
      docker start "$name" || echo "❌ Failed to restart container $name"
    fi
  fi

  # notify_kuma "$kuma_id" "up"
  echo "✅ Maintenance complete for $name"
  echo "----------------------------------"
done