#!/usr/bin/env bash

set -Eeuo pipefail

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly APP_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly BRANCH="${RMS_DEPLOY_BRANCH:-main}"
readonly SERVICE="${RMS_API_SERVICE:-rms-api.service}"
readonly HEALTH_URL="${RMS_HEALTH_URL:-http://127.0.0.1:3000/api/health/ready}"
readonly DEPLOY_KEY="${RMS_DEPLOY_KEY:-${HOME}/.ssh/rms_github_uat}"

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

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

# Apache serves apps/<app>/dist straight off disk, so building there put the new
# screens in front of staff the moment the build finished — while the old API
# was still running, through the whole smoke suite, and for good if a smoke
# failed. Each front end is built beside the live one instead and swapped in only
# once the new API answers. The one it replaces is kept as dist.prev, so going
# back is two renames.
readonly FRONTENDS=(admin portal)

publish_frontends() {
  local app dir
  for app in "${FRONTENDS[@]}"; do
    dir="${APP_DIR}/apps/${app}"
    rm -rf "${dir}/dist.prev"
    if [[ -d "${dir}/dist" ]]; then mv "${dir}/dist" "${dir}/dist.prev"; fi
    mv "${dir}/dist.next" "${dir}/dist"
  done
}

command -v git >/dev/null || fail 'git is not installed'
command -v npm >/dev/null || fail 'npm is not installed'
command -v curl >/dev/null || fail 'curl is not installed'
command -v flock >/dev/null || fail 'flock is not installed'
[[ -f "${APP_DIR}/.env" ]] || fail "${APP_DIR}/.env is missing"
[[ -f "${DEPLOY_KEY}" ]] || fail "GitHub deploy key is missing: ${DEPLOY_KEY}"

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

cd "${APP_DIR}"

if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
  fail 'tracked files have local changes; commit or discard them before deploying'
fi

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

# playwright ships no postinstall, so `npm ci` leaves the JS wrapper with no
# browser behind it and the API boots fine right up until somebody prints a
# debit note. Skipped when the host is set up to use its own Chrome.
# Read from .env, not the deploy shell — that is where the service gets them.
if grep -Eq '^[[:space:]]*PDF_BROWSER_(EXECUTABLE|CHANNEL)=[^[:space:]]' "${APP_DIR}/.env"; then
  log 'Skipping browser download (.env points at an installed browser)'
else
  log 'Installing the Chromium the debit-note PDF renderer needs'
  npx --yes playwright install --with-deps chromium ||
    npx --yes playwright install chromium ||
    log 'WARNING: could not install Chromium; the readiness check below will say so'
fi

log 'Generating Prisma client'
npm run db:generate

log 'Building shared domain package'
npm run build -w @rms/domain

log 'Building API'
npm run build -w @rms/api

log 'Building admin frontend (not live until the API is up)'
npm run build -w @rms/admin -- --outDir dist.next

log 'Building tenant portal (not live until the API is up)'
npm run build -w @rms/portal -- --outDir dist.next

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

# The smokes are this project's test suite and run against a live database, so
# they belong here rather than in a pre-push hook: this is the first moment the
# migrated UAT database exists. Off by default on hosts that share a database
# with anything else, since each smoke writes and purges its own ZZ fixtures.
if [[ "${RMS_DEPLOY_SMOKE:-1}" == "1" ]]; then
  log 'Running the smoke suite against the migrated database'
  npm run smoke -w @rms/api || fail 'the smoke suite is not green; the deploy stops here. The running API and the front ends are still the previous ones, but the migrations above have been applied.'
else
  log 'Skipping smoke suite (RMS_DEPLOY_SMOKE=0)'
fi

log "Restarting ${SERVICE}"
systemctl --user restart "${SERVICE}"

log 'Waiting for API readiness'
for attempt in {1..30}; do
  if ready="$(curl --fail --silent --show-error "${HEALTH_URL}")"; then
    printf %s\n "${ready}"
    # Before the renderer check: the new API is serving from here on, missing
    # renderer or not, so the screens that go with it have to be live too.
    log 'Publishing the front ends'
    publish_frontends
    # A missing renderer does not stop the service, so the old check passed and
    # the first tenant to open a debit note found out instead. Say it here.
    if [[ "${ready}" == *'"pdfRenderer":"missing"'* ]]; then
      fail "the API is up but cannot print a debit note.
${ready}
Fix on this host with:  npx playwright install --with-deps chromium
or point PDF_BROWSER_EXECUTABLE / PDF_BROWSER_CHANNEL at an installed browser."
    fi
    log "Deployment complete: $(git rev-parse --short HEAD)"
    exit 0
  fi
  sleep 2
done

fail "API did not become ready within 60 seconds; the front ends were left as they were (new builds in apps/*/dist.next). Inspect: journalctl --user -u ${SERVICE} -n 100"
