#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
usage(){ echo 'Usage: ./build [start|configure|build|stop|status|logs|restart] [--admin-email EMAIL --catalog NAME --port PORT --udp-port PORT --base-url URL --bind-address IP --trusted-proxy-ip IP --require-trusted-proxy --access-log --login-ip-limit N]'; }
action=${1:-start}; if [[ $action == --help || $action == -h ]]; then usage; exit; fi
if [[ $action == --* ]]; then action=start; else [[ $# == 0 ]] || shift; fi
# This is a runtime-only installer: missing release metadata is an error, never
# a reason to fall back to compiling from source.
case $action in
 start|build|configure)
  command -v python3 >/dev/null || { echo 'Python 3 required' >&2; exit 1; }
  for arg in "$@"; do
   case $arg in --qa|--publisher-key|--publisher-key=*|--activation-url|--activation-url=*)
    echo 'Customer releases use the embedded publisher key and activation configuration.' >&2; exit 2;;
   esac
  done
  python3 verify_release.py
  python3 configure.py "$@"
  ;;
 stop|status|logs|restart) ;;
 *) usage; exit 2;;
esac
[[ $action != configure ]] || exit 0
command -v docker >/dev/null && docker compose version >/dev/null || { echo 'Docker Engine and Compose v2 required' >&2; exit 1; }
[[ -f .env ]] || { echo 'Run ./build configure first' >&2; exit 1; }
case $action in
 start|build)
  docker image load -i images/runtime.tar
  python3 verify_release.py --images
  [[ $action == build ]] || docker compose up -d --no-build --wait
  ;;
 stop) docker compose stop;; status) docker compose ps;; logs) docker compose logs -f;; restart) docker compose restart;;
esac
[[ $action != start ]] || echo 'Started. See APP_BASE_URL in .env; activate with a valid demo or commercial license in the console.'
