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

usage() {
  cat <<'EOF'
Usage:
  cicd-deploy-node-site --domain DOMAIN [--repo /srv/git/DOMAIN] [--ref main] [--install-cmd 'npm ci --omit=dev'] [--build-cmd 'npm run build'] [--shared-link .env.local] [--healthcheck-path /healthz] [--healthcheck-expect TEXT]
  cicd-deploy-node-site --help
EOF
}

domain=""
repo=""
ref="main"
install_cmd="npm ci --omit=dev"
build_cmd="npm run build"
healthcheck_path="/healthz"
healthcheck_expect='"ok": true'
shared_link=".env.local"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --domain) domain="${2:-}"; shift 2 ;;
    --repo) repo="${2:-}"; shift 2 ;;
    --ref) ref="${2:-}"; shift 2 ;;
    --install-cmd) install_cmd="${2:-}"; shift 2 ;;
    --build-cmd) build_cmd="${2:-}"; shift 2 ;;
    --shared-link) shared_link="${2:-}"; shift 2 ;;
    --healthcheck-path) healthcheck_path="${2:-}"; shift 2 ;;
    --healthcheck-expect) healthcheck_expect="${2:-}"; shift 2 ;;
    --help|-h) usage; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

[[ -n "$domain" ]] || { usage; exit 2; }
[[ $(id -u) -eq 0 ]] || { echo 'Run as root' >&2; exit 1; }

env_file="/etc/node-sites/$domain.env"
[[ -f "$env_file" ]] || { echo "Node site env not found: $env_file" >&2; exit 1; }
# shellcheck disable=SC1090
source "$env_file"

: "${SITE_ROOT:?SITE_ROOT is required}"
: "${NODE_VERSION:?NODE_VERSION is required}"
: "${PORT:?PORT is required}"

if [[ -z "$repo" ]]; then
  repo="/srv/git/$domain"
fi

service_name="node-site@$domain.service"
healthcheck_url="http://127.0.0.1:$PORT$healthcheck_path"

exec /usr/local/bin/deploy-node-release \
  --site-root "$SITE_ROOT" \
  --repo "$repo" \
  --ref "$ref" \
  --node-version "$NODE_VERSION" \
  --service "$service_name" \
  --install-cmd "$install_cmd" \
  --build-cmd "$build_cmd" \
  --shared-link "$shared_link" \
  --healthcheck-url "$healthcheck_url" \
  --healthcheck-expect "$healthcheck_expect"
