#!/usr/bin/env bash
set -euo pipefail

RUNTIME_SERVER=/var/www/texise.com/public_html/texise-data/runtime/current/server
ENV_FILE=/etc/texise/texise.env

usage() {
  cat <<'TXT'
Usage: texise-saas <status|preflight|admin-create|logs>

  status     Show service status and /api/health when available.
  preflight  Test configured MySQL, run idempotent migrations and validate runtime storage.
  admin-create  Explicitly create/reset admin@texise.com; password is read interactively from stdin.
  logs       Show the latest trusted API journal entries.
TXT
}

run_preflight() {
  [[ -f "${RUNTIME_SERVER}/saas-preflight.mjs" ]] || {
    echo '[TeXise error] Active runtime does not contain the SaaS preflight command. Install the current release first.' >&2
    exit 1
  }
  systemd-run --quiet --wait --collect --pipe \
    --unit="texise-saas-preflight-$$" \
    --property=User=texise \
    --property=Group=texise \
    --property="WorkingDirectory=${RUNTIME_SERVER}" \
    --property="EnvironmentFile=${ENV_FILE}" \
    --property=NoNewPrivileges=yes \
    /usr/bin/node "${RUNTIME_SERVER}/saas-preflight.mjs"
}

case "${1:-}" in
  status)
    systemctl --no-pager --full status texise.service || true
    echo
    curl --fail --silent --show-error http://127.0.0.1:3100/api/health || true
    echo
    ;;
  preflight)
    run_preflight
    ;;
  admin-create)
    [[ -f "${RUNTIME_SERVER}/saas-admin-create.mjs" ]] || { echo '[TeXise error] Active runtime does not contain admin provisioning.' >&2; exit 1; }
    systemd-run --quiet --wait --collect --pty \
      --unit="texise-saas-admin-create-$$" \
      --property=User=texise --property=Group=texise \
      --property="WorkingDirectory=${RUNTIME_SERVER}" \
      --property="EnvironmentFile=${ENV_FILE}" \
      --property=NoNewPrivileges=yes \
      /usr/bin/node "${RUNTIME_SERVER}/saas-admin-create.mjs"
    ;;
  logs)
    journalctl -u texise.service -n 100 --no-pager -o cat
    ;;
  *) usage; exit 2 ;;
esac
