#!/usr/bin/env bash

# Regenerate Admin + Tenant UAT passwords, write them to the credentials file,
# and update the hashes in the database. Use when ~/.config/rms/uat-credentials.txt
# no longer matches what the API will accept.

set -Eeuo pipefail

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly APP_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly CREDENTIALS_FILE="${HOME}/.config/rms/uat-credentials.txt"
readonly DOMAIN="property.e-inv.link"

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

[[ "$(id -un)" == 'itdpt' ]] || fail 'run this script as the itdpt user'
[[ -f "${APP_DIR}/.env" ]] || fail "${APP_DIR}/.env is missing"
[[ -d "${APP_DIR}/node_modules" ]] || fail 'dependencies missing; run ./scripts/deploy-uat.sh first'

mkdir -p "$(dirname -- "${CREDENTIALS_FILE}")"
chmod 700 "$(dirname -- "${CREDENTIALS_FILE}")"

admin_password="$(openssl rand -hex 12)"
tenant_password="$(openssl rand -hex 12)"

cleanup() {
  unset admin_password tenant_password
}
trap cleanup EXIT

cd "${APP_DIR}/apps/api"

printf 'Updating admin@rms.local...\n'
npx dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/set-user-password.ts \
  --email admin@rms.local --password "${admin_password}"

printf 'Updating tenant@rms.local...\n'
npx dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/set-user-password.ts \
  --email tenant@rms.local --password "${tenant_password}"

umask 077
cat >"${CREDENTIALS_FILE}" <<EOF
RMS UAT credentials
URL: https://${DOMAIN}

Admin
Email: admin@rms.local
Password: ${admin_password}

Tenant portal
URL: https://${DOMAIN}/portal/
Email: tenant@rms.local
Password: ${tenant_password}
EOF
chmod 600 "${CREDENTIALS_FILE}"

printf '\nPasswords reset.\n'
printf '  Credentials: %s\n' "${CREDENTIALS_FILE}"
printf '  Wait ~1 minute if you recently hit Too Many Requests, then log in.\n'
