#!/usr/bin/env bash
set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-player@shineup.me}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
TODAY="$(date +%F)"
DEST_NAME="${DEST_NAME:-${TODAY}}"
DEST_DIR="${ROOT_DIR}/archive/${DEST_NAME}"
RSYNC_REMOTE_SUDO=(--rsync-path="sudo -n rsync")

mkdir -p "${DEST_DIR}"

echo "[1/4] Создаю структуру бэкапа: ${DEST_DIR}"
mkdir -p "${DEST_DIR}/home-player" "${DEST_DIR}/etc-system" "${DEST_DIR}/var-lib/docker-images"

echo "[2/4] Копирую основные данные /home/player"
rsync -aH --delete \
  "${RSYNC_REMOTE_SUDO[@]}" \
  --exclude='SHiNE/shine-server/logs/' \
  --exclude='SHiNE/**/.elaira_logs/' \
  --exclude='**/*.log' \
  "${REMOTE_HOST}:/home/player/SHiNE/" "${DEST_DIR}/home-player/SHiNE/"

rsync -aH --delete "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/home/player/sites/" "${DEST_DIR}/home-player/sites/"
rsync -aH --delete "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/home/player/gitea/" "${DEST_DIR}/home-player/gitea/"
rsync -aH --delete "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/home/player/agent-memory/" "${DEST_DIR}/home-player/agent-memory/"

echo "[3/4] Копирую системные конфиги"
rsync -aH --delete "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/etc/caddy/" "${DEST_DIR}/etc-system/caddy/"
rsync -aH --delete "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/var/lib/caddy/" "${DEST_DIR}/var-lib/caddy/"
rsync -aH "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/etc/turnserver.conf" "${DEST_DIR}/etc-system/turnserver.conf"
rsync -aH "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/etc/systemd/system/shine-server.service" "${DEST_DIR}/etc-system/"
rsync -aH "${RSYNC_REMOTE_SUDO[@]}" "${REMOTE_HOST}:/etc/systemd/system/agent-memory.service" "${DEST_DIR}/etc-system/"
ssh "${REMOTE_HOST}" 'sudo -n docker image save gitea/gitea:1.22.6' > "${DEST_DIR}/var-lib/docker-images/gitea_gitea_1.22.6.tar"

echo "[4/4] Создаю манифест"
{
  echo "backup_date=${TODAY}"
  echo "remote_host=${REMOTE_HOST}"
  echo "created_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo
  echo "sizes:"
  du -sh "${DEST_DIR}/home-player/SHiNE" || true
  du -sh "${DEST_DIR}/home-player/sites" || true
  du -sh "${DEST_DIR}/home-player/gitea" || true
  du -sh "${DEST_DIR}/home-player/agent-memory" || true
  du -sh "${DEST_DIR}/etc-system" || true
  du -sh "${DEST_DIR}/var-lib/caddy" || true
  du -sh "${DEST_DIR}/var-lib/docker-images" || true
  echo
  echo "total:"
  du -sh "${DEST_DIR}" || true
} > "${DEST_DIR}/MANIFEST.txt"

echo "Готово: ${DEST_DIR}"
