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

verify_only=false
if test "$#" -eq 2 && test "$2" = "--verify-only"; then
    archive="$1"
    staging_dir="$(mktemp -d "$(dirname "${archive}")/.ikar-verify-XXXXXX")"
    verify_only=true
elif test "$#" -eq 3 && test "$3" = "--confirm-restore"; then
    archive="$1"
    target_dir="$2"
    mkdir -p "$(dirname "${target_dir}")"
    staging_dir="$(mktemp -d "${target_dir}.restore-XXXXXX")"
else
    echo "Usage: $0 <backup.tar.gz> --verify-only" >&2
    echo "   or: $0 <backup.tar.gz> <target-data-dir> --confirm-restore" >&2
    exit 64
fi

cleanup() {
    rm -rf -- "${staging_dir}"
}
trap cleanup EXIT

test -f "${archive}"
test -f "${archive}.sha256"
(cd "$(dirname "${archive}")" && sha256sum -c "$(basename "${archive}.sha256")")
tar -C "${staging_dir}" -xzf "${archive}"
test -f "${staging_dir}/Data/ikar.db"
test "$(sqlite3 "${staging_dir}/Data/ikar.db" 'PRAGMA integrity_check;')" = "ok"

if test "${verify_only}" = true; then
    echo "Backup verification completed successfully."
    exit 0
fi

if test -e "${target_dir}"; then
    mv "${target_dir}" "${target_dir}.before-restore-$(date -u +%Y%m%dT%H%M%SZ)"
fi
mv "${staging_dir}/Data" "${target_dir}"
rmdir "${staging_dir}"
trap - EXIT

echo "Restore completed. Start the Ikar server and verify /health before removing the pre-restore directory."
