#!/usr/bin/env bash
set -Eeuo pipefail
ROOT="$(pwd)"
BACKUP_ROOT="$ROOT/lifebook-backups"
LATEST="${1:-}"
if [[ -z "$LATEST" ]]; then
  LATEST="$(find "$BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort | tail -1)"
fi
[[ -n "$LATEST" && -d "$LATEST" ]] || { echo "No backup directory found."; exit 1; }
echo "Restoring application files from: $LATEST"
for item in "$LATEST"/* "$LATEST"/.[!.]*; do
  [[ -e "$item" ]] || continue
  base="$(basename "$item")"
  case "$base" in .env|.htaccess|.user.ini|.well-known) continue ;; esac
  rm -rf "$ROOT/$base"; cp -a "$item" "$ROOT/$base"
done
mkdir -p "$ROOT/tmp" && touch "$ROOT/tmp/restart.txt"
echo "Application files restored. Database migrations are not automatically reversed."
