#!/bin/bash
set -euo pipefail

# -------- Configuration --------
COMPOSE_FILE="/opt/appdata/.docker-compose/docker-compose.yml"
APP_DIR="/opt/appdata/uptime"
DB_FILE="$APP_DIR/config/kuma.db"
BCK_DST="$APP_DIR/backup"
HC_ID="Fn5Pc5WGai"
KUMA_PUSH_URL="https://uptime.noxs.me/api/push/$HC_ID"
BCK_TOOL="sqlite dump"
RETENTION=7
NOW=$(date +%F_%H-%M)
DUMP_FILE="$BCK_DST/kuma_$NOW.dump.gz"

# -------- Root Check --------
if [[ $EUID -ne 0 ]]; then
  echo "❌ This script must be run as root."
  curl -s -X GET "$KUMA_PUSH_URL?status=down" > /dev/null
  exit 1
fi

# -------- Initial Checks --------

# Install sqlite3 if missing
if ! command -v sqlite3 >/dev/null 2>&1; then
  echo "ℹ️ sqlite3 not found. Attempting to install..."
  if command -v apt >/dev/null 2>&1; then
    apt update && apt install -y sqlite3
  else
    echo "❌ Package manager not supported. Please install sqlite3 manually."
    curl -s -X GET "$KUMA_PUSH_URL?status=down" > /dev/null
    exit 1
  fi
fi

# Check app directory
if [[ ! -d "$APP_DIR" ]]; then
  echo "❌ Application directory not found: $APP_DIR"
  curl -s -X GET "$KUMA_PUSH_URL?status=down" > /dev/null
  exit 1
fi

# Check database file
if [[ ! -f "$DB_FILE" ]]; then
  echo "❌ Database file not found: $DB_FILE"
  curl -s -X GET "$KUMA_PUSH_URL?status=down" > /dev/null
  exit 1
fi

# Ensure backup directory exists
mkdir -p "$BCK_DST"

# -------- Dump & Rotate --------

echo "🗃️ Dumping Uptime data with $BCK_TOOL..."
if sqlite3 "$DB_FILE" .dump | gzip -c > "$DUMP_FILE"; then
  echo "✅ Dump successful: $DUMP_FILE"

  # Rotate
  echo "♻️ Rotating old dumps..."
  ls -1t "$BCK_DST"/kuma_*.dump.gz | tail -n +$((RETENTION + 1)) | xargs -r rm -f

  # Notify
  echo "📡 Sending success notification to Uptime-Kuma..."
  curl -s -X GET "$KUMA_PUSH_URL" > /dev/null && echo "✅ Notification sent."
  echo "✅ Uptime backup complete."
  exit 0
else
  echo "❌ $BCK_TOOL failed!"
  curl -s -X GET "$KUMA_PUSH_URL?status=down" > /dev/null && echo "❌ Failure notification sent."
  exit 1
fi