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

: "${BACKUP_BUNDLE:?Set BACKUP_BUNDLE to a verified backup bundle directory}"
: "${RESTORE_DB_NAME:?Set RESTORE_DB_NAME to a disposable database beginning with microfinance_restore_}"
: "${RESTORE_DB_ADMIN_USER:?Set RESTORE_DB_ADMIN_USER to the restore-test database administrator}"

RESTORE_DB_HOST="${RESTORE_DB_HOST:-127.0.0.1}"
RESTORE_DB_PORT="${RESTORE_DB_PORT:-3306}"
RESTORE_DB_ADMIN_PASSWORD="${RESTORE_DB_ADMIN_PASSWORD:-}"

if [[ ! "${RESTORE_DB_NAME}" =~ ^microfinance_restore_[A-Za-z0-9_]+$ ]]; then
    echo "RESTORE_DB_NAME must begin with microfinance_restore_ and contain only letters, numbers, and underscores." >&2
    exit 2
fi

if [[ "${RESTORE_DB_NAME}" == "${DB_DATABASE:-}" ]]; then
    echo "Restore drill database must not equal DB_DATABASE." >&2
    exit 2
fi

if [[ ! -f "${BACKUP_BUNDLE}/manifest.json" || ! -f "${BACKUP_BUNDLE}/database.sql" ]]; then
    echo "BACKUP_BUNDLE is missing manifest.json or database.sql." >&2
    exit 2
fi

php artisan security:backup-verify "${BACKUP_BUNDLE}" >/dev/null

driver="$(php -r '$m=json_decode(file_get_contents($argv[1]."/manifest.json"), true); echo $m["database"]["driver"] ?? "";' "${BACKUP_BUNDLE}")"
if [[ "${driver}" != "mysql" && "${driver}" != "mariadb" ]]; then
    echo "Restore drill expects a MySQL/MariaDB backup, got ${driver:-unknown}." >&2
    exit 2
fi

export MYSQL_PWD="${RESTORE_DB_ADMIN_PASSWORD}"
mysql_cmd=(mysql --protocol=TCP --host="${RESTORE_DB_HOST}" --port="${RESTORE_DB_PORT}" --user="${RESTORE_DB_ADMIN_USER}")

cleanup() {
    "${mysql_cmd[@]}" --execute="DROP DATABASE IF EXISTS \`${RESTORE_DB_NAME}\`;" >/dev/null 2>&1 || true
}
trap cleanup EXIT

cleanup
"${mysql_cmd[@]}" --execute="CREATE DATABASE \`${RESTORE_DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
"${mysql_cmd[@]}" "${RESTORE_DB_NAME}" < "${BACKUP_BUNDLE}/database.sql"

for table in migrations businesses users; do
    count="$("${mysql_cmd[@]}" --batch --skip-column-names --execute="SELECT COUNT(*) FROM \`${table}\`;" "${RESTORE_DB_NAME}")"
    if [[ ! "${count}" =~ ^[0-9]+$ ]]; then
        echo "Restore verification failed for table ${table}." >&2
        exit 1
    fi
done

printf 'Backup restore drill passed for bundle %s using disposable database %s\n' "${BACKUP_BUNDLE}" "${RESTORE_DB_NAME}"
