#!/bin/sh
set -eu

compose_file="${COMPOSE_FILE:-docker-compose.yml}"
source_name="${1:-latest-s3}"
confirmation_phrase="replace-bowli-production-database"

if [ ! -f "$compose_file" ]; then
    echo "Run this command from the daily-meal-api directory." >&2
    exit 1
fi

echo "This operation will replace the production database."
echo "Backup source: $source_name"
printf "Type %s to continue: " "$confirmation_phrase"
read -r confirmation

if [ "$confirmation" != "$confirmation_phrase" ]; then
    echo "Restoration cancelled."
    exit 1
fi

docker compose -f "$compose_file" stop app worker scheduler db-backup

if ! RESTORE_CONFIRM="$confirmation_phrase" docker compose \
    -f "$compose_file" \
    --profile restore \
    run --rm db-restore "$source_name"
then
    echo "Restoration failed. The application remains stopped to protect the database." >&2
    echo "Inspect the logs, then restart it manually only when the database is safe." >&2
    exit 1
fi

docker compose -f "$compose_file" up -d app worker scheduler db-backup

echo "Application restarted after database restoration."
