#!/bin/bash
set -euo pipefail

SERVICE_NAME="smg"
APP_DIR="/home/smg/smgplayer"
BACKUP_DIR="${APP_DIR}/backups"
DB_FILES=("signage.db" "logsDB.db")
KEEP_BACKUPS=3   # Son kaç yedek kalsın

STAMP="$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
shopt -s nullglob   # Eşleşme yoksa glob boş döner, hata çıkmaz

echo "[*] Stopping service: ${SERVICE_NAME}"
sudo systemctl stop "$SERVICE_NAME"

restore_and_start() {
  local db_file="$1"
  echo "[!] Restoring backup for ${db_file}"
  cp -a "${BACKUP_DIR}/${db_file}.${STAMP}.bak" "${APP_DIR}/${db_file}" || true
}

cleanup_backups() {
  local db_file="$1"
  # En yeni → en eski sırala
  mapfile -t files < <(ls -1t "${BACKUP_DIR}/${db_file}."*.bak 2>/dev/null || true)
  local count="${#files[@]}"

  if (( count > KEEP_BACKUPS )); then
    echo "[*] Cleanup: keeping ${KEEP_BACKUPS} backups for ${db_file}, removing $((count-KEEP_BACKUPS)) older"
    for (( i=KEEP_BACKUPS; i<count; i++ )); do
      echo "    - rm ${files[$i]}"
      rm -f "${files[$i]}" || true
    done
  else
    echo "[*] Cleanup: ${db_file} has ${count} backup(s), nothing to remove"
  fi
}

for DB_NAME in "${DB_FILES[@]}"; do
  DB_PATH="${APP_DIR}/${DB_NAME}"
  BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}.${STAMP}.bak"

  echo ""
  echo "=== Processing ${DB_NAME} ==="

  if [ ! -f "$DB_PATH" ]; then
    echo "[!] WARNING: ${DB_PATH} not found, skipping."
    continue
  fi

  echo "[*] Backing up → ${BACKUP_FILE}"
  cp -a "$DB_PATH" "$BACKUP_FILE"

  echo "[*] VACUUM"
  if ! sqlite3 "$DB_PATH" "VACUUM;"; then
    echo "[x] VACUUM failed for ${DB_NAME}"
    restore_and_start "$DB_NAME"
    continue
  fi

  echo "[*] REINDEX"
  if ! sqlite3 "$DB_PATH" "REINDEX;"; then
    echo "[x] REINDEX failed for ${DB_NAME}"
    restore_and_start "$DB_NAME"
    continue
  fi

  echo "[*] integrity_check"
  if [ "$(sqlite3 "$DB_PATH" "PRAGMA integrity_check;")" != "ok" ]; then
    echo "[x] integrity_check failed for ${DB_NAME}"
    restore_and_start "$DB_NAME"
    continue
  fi

  echo "[✓] ${DB_NAME} maintenance completed successfully."

  # --- Yedek temizlik (sonda yap) ---
  cleanup_backups "$DB_NAME"
done

echo ""
echo "[*] Starting service: ${SERVICE_NAME}"
sudo systemctl start "$SERVICE_NAME"

echo "[✓] All done."
