#!/usr/bin/env bash

set -Eeuo pipefail

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly APP_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly ENV_FILE="${APP_DIR}/.env"
readonly CREDENTIALS_FILE="${HOME}/.config/rms/uat-credentials.txt"
readonly DEPLOY_KEY="${HOME}/.ssh/rms_github_uat"
readonly BRANCH="main"
readonly SERVICE="rms-api.service"
readonly EXPECTED_DATABASE="rms2"
readonly HEALTH_URL="http://127.0.0.1:3000/api/health/ready"
readonly BACKUP_DIR="${HOME}/.local/share/rms/backups"

service_stopped=0
backup_file=''

log() {
  printf '\n[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

fail() {
  printf '\nUAT database reset failed: %s\n' "$*" >&2
  exit 1
}

cleanup() {
  status=$?
  unset db_password admin_password tenant_password

  if [[ "${status}" -ne 0 ]]; then
    if [[ -n "${backup_file}" ]]; then
      printf 'Database backup: %s\n' "${backup_file}" >&2
    fi
    if [[ "${service_stopped}" -eq 1 ]]; then
      printf 'Attempting to restart %s...\n' "${SERVICE}" >&2
      systemctl --user start "${SERVICE}" || true
    fi
  fi
}
trap cleanup EXIT

[[ "$(id -un)" == 'itdpt' ]] || fail 'run this script as the itdpt user, not root'
[[ -f "${ENV_FILE}" ]] || fail "${ENV_FILE} is missing"
[[ -f "${CREDENTIALS_FILE}" ]] || fail "${CREDENTIALS_FILE} is missing"
[[ -f "${DEPLOY_KEY}" ]] || fail "${DEPLOY_KEY} is missing"

for command_name in git npm node mysql mysqldump gzip curl flock; do
  command -v "${command_name}" >/dev/null || fail "${command_name} is not installed"
done

exec 9>"/tmp/rms-uat-deploy.lock"
flock -n 9 || fail 'another deployment or reset is already running'

read_env_url_field() {
  node - "${ENV_FILE}" "$1" <<'NODE'
const fs = require('node:fs');

const envFile = process.argv[2];
const field = process.argv[3];
const content = fs.readFileSync(envFile, 'utf8');
const match = content.match(/^DATABASE_URL=(?:"([^"]+)"|'([^']+)'|([^\r\n]+))$/m);
if (!match) process.exit(2);

const url = new URL(match[1] ?? match[2] ?? match[3]);
const fields = {
  host: url.hostname,
  port: url.port || '3306',
  database: url.pathname.replace(/^\//, ''),
  username: decodeURIComponent(url.username),
  password: decodeURIComponent(url.password),
};
if (!(field in fields)) process.exit(3);
process.stdout.write(fields[field]);
NODE
}

read_credential_password() {
  node - "${CREDENTIALS_FILE}" "$1" <<'NODE'
const fs = require('node:fs');

const content = fs.readFileSync(process.argv[2], 'utf8');
const index = Number(process.argv[3]);
const passwords = [...content.matchAll(/^Password:\s*(.+)$/gm)].map((match) => match[1].trim());
if (!passwords[index]) process.exit(2);
process.stdout.write(passwords[index]);
NODE
}

db_host="$(read_env_url_field host)" || fail 'could not read DATABASE_URL host'
db_port="$(read_env_url_field port)" || fail 'could not read DATABASE_URL port'
db_name="$(read_env_url_field database)" || fail 'could not read DATABASE_URL database'
db_user="$(read_env_url_field username)" || fail 'could not read DATABASE_URL username'
db_password="$(read_env_url_field password)" || fail 'could not read DATABASE_URL password'
admin_password="$(read_credential_password 0)" || fail 'could not read the admin UAT password'
tenant_password="$(read_credential_password 1)" || fail 'could not read the tenant UAT password'

[[ "${db_name}" == "${EXPECTED_DATABASE}" ]] ||
  fail "refusing to reset ${db_name}; expected ${EXPECTED_DATABASE}"
[[ "${db_host}" == '125.215.175.139' ]] ||
  fail "refusing to reset unexpected database host ${db_host}"
[[ "${db_name}" =~ ^[a-zA-Z0-9_]+$ ]] || fail 'database name contains unsafe characters'

printf 'WARNING: this permanently deletes all data in %s@%s:%s/%s.\n' \
  "${db_user}" "${db_host}" "${db_port}" "${db_name}"
printf 'Uploads under /var/lib/rms are not deleted and may become orphaned.\n'
read -r -p "Type RESET ${db_name} to continue: " confirmation
[[ "${confirmation}" == "RESET ${db_name}" ]] || fail 'confirmation did not match; no changes were made'

mkdir -p "${BACKUP_DIR}"
chmod 700 "${BACKUP_DIR}"
backup_file="${BACKUP_DIR}/${db_name}-$(date '+%Y%m%d-%H%M%S').sql.gz"

log "Backing up ${db_name}"
MYSQL_PWD="${db_password}" mysqldump \
  --protocol=TCP \
  --host="${db_host}" \
  --port="${db_port}" \
  --user="${db_user}" \
  --single-transaction \
  --routines \
  --triggers \
  --no-tablespaces \
  "${db_name}" | gzip -9 >"${backup_file}" || {
  # Nothing usable was written, so do not leave behind a file the failure
  # handler would then announce as a backup.
  rm -f "${backup_file}"
  backup_file=''
  fail 'database backup failed; no reset was performed'
}

# A gzip of nothing is still a valid gzip, so size is the only proof the dump
# produced something — and this is the last moment the original still exists.
if [[ "$(stat -c %s "${backup_file}")" -lt 1024 ]]; then
  rm -f "${backup_file}"
  backup_file=''
  fail 'database backup came back empty; no reset was performed'
fi
chmod 600 "${backup_file}"

cd "${APP_DIR}"
[[ -z "$(git status --porcelain --untracked-files=no)" ]] ||
  fail 'tracked files have local changes; no reset was performed'

export GIT_SSH_COMMAND="ssh -i ${DEPLOY_KEY} -o IdentitiesOnly=yes"

log "Fetching origin/${BRANCH}"
git fetch origin "${BRANCH}"
git merge --ff-only "origin/${BRANCH}"

log 'Installing locked dependencies'
npm ci --no-audit --no-fund

log 'Generating Prisma client'
npm run db:generate

log 'Building all applications before downtime'
npm run build -w @rms/domain
npm run build -w @rms/api
npm run build -w @rms/admin
npm run build -w @rms/portal

log "Stopping ${SERVICE}"
systemctl --user stop "${SERVICE}"
service_stopped=1

log "Dropping and recreating ${db_name}"
MYSQL_PWD="${db_password}" mysql \
  --connect-timeout=10 \
  --protocol=TCP \
  --host="${db_host}" \
  --port="${db_port}" \
  --user="${db_user}" \
  --execute="DROP DATABASE \`${db_name}\`; CREATE DATABASE \`${db_name}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ||
  fail 'could not recreate the database'

log 'Applying the latest migrations'
npm run prisma:deploy -w @rms/api

log 'Applying the latest seed data with the existing UAT passwords'
SEED_ADMIN_PASSWORD="${admin_password}" \
SEED_TENANT_PASSWORD="${tenant_password}" \
  npm run db:seed

log "Starting ${SERVICE}"
systemctl --user start "${SERVICE}"
service_stopped=0

log 'Waiting for API readiness'
for attempt in {1..30}; do
  if curl --fail --silent --show-error "${HEALTH_URL}"; then
    printf '\n'
    log "Reset complete: $(git rev-parse --short HEAD)"
    printf 'Database backup: %s\n' "${backup_file}"
    exit 0
  fi
  sleep 2
done

service_stopped=1
fail "API did not become ready within 60 seconds; inspect: journalctl --user -u ${SERVICE} -n 100"
