#!/bin/bash
# Restore the database and files from S3. For the restore TEST on a fresh
# instance, or for real recovery.
#   sudo greenathon-restore                       # latest dump
#   sudo greenathon-restore db-2026-12-01-0230.sql.gz
# The target must already have its .env with the SAME APP_KEY and BLIND_INDEX_KEY.
set -Eeuo pipefail
source /etc/greenathon/backup.env
APP=${GREENATHON_APP:-/var/www/greenathon}
APP_USER=${GREENATHON_USER:-greenathon}
[[ $EUID -eq 0 ]] || { echo "Run with sudo." >&2; exit 1; }

KEY=${1:-$(aws s3 ls "s3://$BACKUP_BUCKET/db/" | awk '{print $4}' | sort | tail -1)}
[[ -n $KEY ]] || { echo "No dumps found in s3://$BACKUP_BUCKET/db/" >&2; exit 1; }
echo "This REPLACES database '$DB_NAME' with $KEY and restores uploaded files."
read -r -p "Type RESTORE to continue: " ok
[[ $ok == RESTORE ]] || exit 1

TMP=$(mktemp -d)
aws s3 cp "s3://$BACKUP_BUCKET/db/$KEY" "$TMP/$KEY" --only-show-errors
[[ -e $APP/current ]] && sudo -u "$APP_USER" -H php "$APP/current/artisan" down || true
gunzip -c "$TMP/$KEY" | mysql --defaults-extra-file="$APP/shared/.my.cnf" "$DB_NAME"
aws s3 sync "s3://$BACKUP_BUCKET/files/" "$APP/shared/storage/app/private" --only-show-errors
chown -R "$APP_USER:$APP_USER" "$APP/shared/storage"
rm -rf "$TMP"
if [[ -e $APP/current ]]; then
    sudo -u "$APP_USER" -H php "$APP/current/artisan" optimize
    sudo -u "$APP_USER" -H php "$APP/current/artisan" up
fi
echo "Restored $KEY. Check: php artisan greenathon:content-check, and that phone numbers show decrypted in the panel."
