#!/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 DB_HOST="125.215.175.139"
readonly DB_PORT="3306"
readonly DB_NAME="rms2"
readonly DB_USER="itdpt"

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

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

command -v mysql >/dev/null || fail 'mysql client is not installed'
command -v node >/dev/null || fail 'node is not installed'

read -r -s -p "Password for ${DB_USER}@${DB_HOST}: " db_password
printf '\n'
[[ -n "${db_password}" ]] || fail 'password cannot be empty'

cleanup() {
  unset db_password encoded_password
}
trap cleanup EXIT

printf 'Testing remote MySQL connection...\n'
db_version="$(
  MYSQL_PWD="${db_password}" mysql \
    --connect-timeout=10 \
    --protocol=TCP \
    --host="${DB_HOST}" \
    --port="${DB_PORT}" \
    --user="${DB_USER}" \
    --batch --skip-column-names \
    --execute='SELECT VERSION();'
)" || fail 'could not connect; check password, firewall and MySQL grants'

[[ "${db_version}" == 8.* ]] || fail "MySQL 8 is required; server reported ${db_version}"

schema_exists="$(
  MYSQL_PWD="${db_password}" mysql \
    --connect-timeout=10 \
    --protocol=TCP \
    --host="${DB_HOST}" \
    --port="${DB_PORT}" \
    --user="${DB_USER}" \
    --batch --skip-column-names \
    --execute="SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = '${DB_NAME}';"
)" || fail 'could not inspect database schemas'

if [[ "${schema_exists}" == '0' ]]; then
  printf 'Creating database %s...\n' "${DB_NAME}"
  MYSQL_PWD="${db_password}" mysql \
    --connect-timeout=10 \
    --protocol=TCP \
    --host="${DB_HOST}" \
    --port="${DB_PORT}" \
    --user="${DB_USER}" \
    --execute="CREATE DATABASE \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ||
    fail "${DB_USER} does not have permission to create ${DB_NAME}"
fi

table_count="$(
  MYSQL_PWD="${db_password}" mysql \
    --connect-timeout=10 \
    --protocol=TCP \
    --host="${DB_HOST}" \
    --port="${DB_PORT}" \
    --user="${DB_USER}" \
    --database="${DB_NAME}" \
    --batch --skip-column-names \
    --execute="SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '${DB_NAME}';"
)" || fail 'could not inspect the target database'

[[ "${table_count}" == '0' ]] || fail "${DB_NAME} is not empty (${table_count} tables); no changes were made"

encoded_password="$(node -e 'process.stdout.write(encodeURIComponent(process.argv[1]))' "${db_password}")"
new_database_url="mysql://${DB_USER}:${encoded_password}@${DB_HOST}:${DB_PORT}/${DB_NAME}"
backup_file="${ENV_FILE}.pre-remote-db-$(date '+%Y%m%d-%H%M%S')"

cp --preserve=mode,timestamps "${ENV_FILE}" "${backup_file}"
umask 077

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

const envFile = process.argv[2];
const databaseUrl = process.argv[3];
const current = fs.readFileSync(envFile, 'utf8');
const replacement = `DATABASE_URL="${databaseUrl}"`;
const updated = /^DATABASE_URL=.*$/m.test(current)
  ? current.replace(/^DATABASE_URL=.*$/m, replacement)
  : `${current.trimEnd()}\n${replacement}\n`;
const temporary = `${envFile}.switching`;

fs.writeFileSync(temporary, updated, { mode: 0o600 });
fs.renameSync(temporary, envFile);
NODE

chmod 600 "${ENV_FILE}"

printf '\nRemote database connection configured.\n'
printf '  Target: %s@%s:%s/%s\n' "${DB_USER}" "${DB_HOST}" "${DB_PORT}" "${DB_NAME}"
printf '  Backup: %s\n' "${backup_file}"
printf '  The existing local rms_uat database was not changed.\n'
