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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/pd_backup_lib.sh"

ssh_opts="$(ssh_args)"
remote_root="$SERENITY_BACKUP_HOST:$SERENITY_BACKUP_ROOT"

# shellcheck disable=SC2086
ssh $ssh_opts "$SERENITY_BACKUP_HOST" mkdir -p \
  "$SERENITY_BACKUP_ROOT/appdata" \
  "$SERENITY_BACKUP_ROOT/databases" \
  "$SERENITY_BACKUP_ROOT/tank-docker" \
  "$SERENITY_BACKUP_ROOT/db-dumps"

rsync_cmd=(
  rsync -a --delete
  --exclude '*.sqlite-journal'
  --exclude '*.db-journal'
  --exclude '*.sqlite-wal'
  --exclude '*.db-wal'
  --exclude '*.tmp'
)
rsync_cmd+=( -e "$(ssh_cmd)" )

run_rsync() {
  local label="$1"
  shift
  echo "$label"
  set +e
  "${rsync_cmd[@]}" "$@"
  local rc=$?
  set -e
  if [[ $rc -eq 24 ]]; then
    echo "rsync completed with vanished-file warning (code 24); treating as acceptable for live appdata."
    return 0
  fi
  return $rc
}

run_rsync "Syncing appdata to Serenity" "$PD_APPDATA_ROOT/" "$remote_root/appdata/"

run_rsync "Syncing database volume roots to Serenity" "$PD_DATABASES_ROOT/" "$remote_root/databases/"

run_rsync "Syncing selected tank docker data to Serenity" "$PD_TANK_DOCKER_ROOT/" "$remote_root/tank-docker/"

run_rsync "Syncing DB dumps to Serenity" "$PD_DB_DUMP_ROOT/" "$remote_root/db-dumps/"

echo "Serenity sync complete: $remote_root"
