#!/usr/bin/env bash

set -Eeuo pipefail

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly APP_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly DOMAIN="property.e-inv.link"
readonly TLS_CERT_NAME="property-rms"
readonly SERVICE="rms-api.service"
readonly USER_SYSTEMD_DIR="${HOME}/.config/systemd/user"
readonly SERVICE_FILE="${USER_SYSTEMD_DIR}/${SERVICE}"
readonly RMS_CONFIG_DIR="${HOME}/.config/rms"
readonly CREDENTIALS_FILE="${RMS_CONFIG_DIR}/uat-credentials.txt"
readonly COMPLETE_MARKER="${RMS_CONFIG_DIR}/uat-host-setup-complete"
readonly HTTP_CONFIG="/etc/apache2/sites-available/property.conf"
readonly HTTPS_CONFIG="/etc/apache2/sites-available/property-le-ssl.conf"

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

[[ "$(id -un)" == 'itdpt' ]] || fail 'run this script as the itdpt user, not root'
[[ -f "${APP_DIR}/.env" ]] || fail "${APP_DIR}/.env is missing; run setup-uat.sh first"
[[ ! -e "${COMPLETE_MARKER}" ]] || fail "setup already completed; marker: ${COMPLETE_MARKER}"

command -v node >/dev/null || fail 'node is not installed'
command -v openssl >/dev/null || fail 'openssl is not installed'
command -v systemctl >/dev/null || fail 'systemctl is not installed'

printf 'Administrator access is required to configure Apache and user-service persistence.\n'
sudo -v

sudo test -f "/etc/letsencrypt/live/${TLS_CERT_NAME}/fullchain.pem" || fail "TLS certificate ${TLS_CERT_NAME} is missing"
sudo test -f "/etc/letsencrypt/live/${TLS_CERT_NAME}/privkey.pem" || fail "TLS private key ${TLS_CERT_NAME} is missing"

mkdir -p "${USER_SYSTEMD_DIR}" "${RMS_CONFIG_DIR}"
chmod 700 "${RMS_CONFIG_DIR}"

node_path="$(command -v node)"
cat >"${SERVICE_FILE}" <<EOF
[Unit]
Description=RMS UAT API
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=${APP_DIR}
Environment=NODE_ENV=production
ExecStart=${node_path} ${APP_DIR}/apps/api/dist/main.js
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=default.target
EOF

sudo loginctl enable-linger itdpt
systemctl --user daemon-reload
systemctl --user enable "${SERVICE}"

if systemctl --user is-active --quiet "${SERVICE}" && [[ -f "${CREDENTIALS_FILE}" ]]; then
  printf '\nAPI and UAT credentials already exist; skipping repeated build and seed.\n'
else
  printf '\nBuilding, migrating and starting RMS...\n'
  "${SCRIPT_DIR}/deploy-uat.sh"

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

  printf '\nCreating UAT reference data and users...\n'
  SEED_ADMIN_PASSWORD="${admin_password}" \
  SEED_TENANT_PASSWORD="${tenant_password}" \
    npm --prefix "${APP_DIR}" run db:seed

  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}"
  unset admin_password tenant_password
fi

timestamp="$(date '+%Y%m%d-%H%M%S')"
http_backup="${HTTP_CONFIG}.pre-rms-${timestamp}"
https_backup="${HTTPS_CONFIG}.pre-rms-${timestamp}"
http_temp="$(mktemp)"
https_temp="$(mktemp)"
apache_switched=0

cleanup() {
  status=$?
  rm -f "${http_temp}" "${https_temp}"
  if [[ "${status}" -ne 0 && "${apache_switched}" -eq 1 ]]; then
    printf '\nRestoring the previous Apache configuration...\n' >&2
    sudo cp "${http_backup}" "${HTTP_CONFIG}"
    sudo cp "${https_backup}" "${HTTPS_CONFIG}"
    sudo systemctl reload apache2 || true
  fi
}
trap cleanup EXIT

sudo cp --preserve=mode,ownership,timestamps "${HTTP_CONFIG}" "${http_backup}"
sudo cp --preserve=mode,ownership,timestamps "${HTTPS_CONFIG}" "${https_backup}"

cat >"${http_temp}" <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN}

    RewriteEngine On
    RewriteRule ^ https://${DOMAIN}%{REQUEST_URI} [R=301,L,NE]

    ErrorLog \${APACHE_LOG_DIR}/property_error.log
    CustomLog \${APACHE_LOG_DIR}/property_access.log combined
</VirtualHost>
EOF

cat >"${https_temp}" <<EOF
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName ${DOMAIN}
    DocumentRoot ${APP_DIR}/apps/admin/dist

    ProxyPreserveHost On
    ProxyPass /api/ http://127.0.0.1:3000/api/
    ProxyPassReverse /api/ http://127.0.0.1:3000/api/
    RequestHeader set X-Forwarded-Proto "https"

    RedirectMatch 301 ^/portal$ /portal/
    Alias /portal/ "${APP_DIR}/apps/portal/dist/"

    <Directory "${APP_DIR}/apps/portal/dist">
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
        FallbackResource /portal/index.html
    </Directory>

    <Directory "${APP_DIR}/apps/admin/dist">
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
        FallbackResource /index.html
    </Directory>

    <Location /api/>
        LimitRequestBody 12582912
    </Location>

    ErrorLog \${APACHE_LOG_DIR}/property_error.log
    CustomLog \${APACHE_LOG_DIR}/property_access.log combined

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/${TLS_CERT_NAME}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${TLS_CERT_NAME}/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
EOF

printf '\nBacking up and switching the %s Apache VirtualHost...\n' "${DOMAIN}"
sudo a2enmod proxy proxy_http headers rewrite ssl >/dev/null
sudo install -o root -g root -m 0644 "${http_temp}" "${HTTP_CONFIG}"
sudo install -o root -g root -m 0644 "${https_temp}" "${HTTPS_CONFIG}"
apache_switched=1

if ! sudo apache2ctl configtest; then
  fail 'Apache config test failed'
fi

if ! sudo systemctl reload apache2; then
  fail 'Apache reload failed'
fi

curl --fail --silent --show-error "https://${DOMAIN}/api/health/ready" >/dev/null ||
  fail 'public API readiness check failed after Apache switch'
curl --fail --silent --show-error "https://${DOMAIN}/" >/dev/null ||
  fail 'admin frontend check failed after Apache switch'
curl --fail --silent --show-error "https://${DOMAIN}/portal/" >/dev/null ||
  fail 'tenant portal check failed after Apache switch'

apache_switched=0
touch "${COMPLETE_MARKER}"
chmod 600 "${COMPLETE_MARKER}"

printf '\nRMS UAT host setup complete.\n'
printf '  Admin:       https://%s/\n' "${DOMAIN}"
printf '  Portal:      https://%s/portal/\n' "${DOMAIN}"
printf '  Credentials: %s\n' "${CREDENTIALS_FILE}"
printf '  Old site remains untouched at /var/www/property.\n'
printf '  Apache backups: %s and %s\n' "${http_backup}" "${https_backup}"
