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

SOURCE_DB="${SOURCE_DB:-ejaarah_db}"
TARGET_DB="${TARGET_DB:-alqudusp16_db}"
PGUSER="${PGUSER:-postgres}"
PGHOST="${PGHOST:-127.0.0.1}"
PGPORT="${PGPORT:-5432}"

echo "Creating database ${TARGET_DB} if needed..."
psql -h "${PGHOST}" -p "${PGPORT}" -U "${PGUSER}" -d postgres -tc "SELECT 1 FROM pg_database WHERE datname = '${TARGET_DB}'" | grep -q 1 \
  || createdb -h "${PGHOST}" -p "${PGPORT}" -U "${PGUSER}" "${TARGET_DB}"

echo "Copying schema and data from ${SOURCE_DB} to ${TARGET_DB}..."
pg_dump -h "${PGHOST}" -p "${PGPORT}" -U "${PGUSER}" --clean --if-exists --no-owner --no-privileges "${SOURCE_DB}" \
  | psql -h "${PGHOST}" -p "${PGPORT}" -U "${PGUSER}" -d "${TARGET_DB}"

APP_SITE_ID="${APP_SITE_ID:-suraualqudus}"
echo "Keeping one-surau focus with default site id: ${APP_SITE_ID}"
psql -h "${PGHOST}" -p "${PGPORT}" -U "${PGUSER}" -d "${TARGET_DB}" <<SQL
UPDATE sites
SET is_subscribed = TRUE
WHERE id = '${APP_SITE_ID}';
SQL

echo "Done. Database ${TARGET_DB} is ready."
