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

APP_PUBLIC_PORT="${APP_PUBLIC_PORT:-8080}"
APP_FRONTEND_PORT="${APP_FRONTEND_PORT:-3000}"
APP_BACKEND_PORT="${APP_BACKEND_PORT:-18080}"
UVICORN_LOOP="${UVICORN_LOOP:-asyncio}"
UVICORN_HTTP="${UVICORN_HTTP:-h11}"
UVICORN_WS="${UVICORN_WS:-websockets}"
BEAVER_HOME="${BEAVER_HOME:-/root/.beaver}"
BEAVER_CONFIG_PATH="${BEAVER_CONFIG_PATH:-$BEAVER_HOME/config.json}"
BEAVER_WORKSPACE="${BEAVER_WORKSPACE:-$BEAVER_HOME/workspace}"
BEAVER_AUTH_FILE="${BEAVER_AUTH_FILE:-$BEAVER_HOME/web_auth_users.json}"
BEAVER_RUNTIME_ENV_FILE="${BEAVER_RUNTIME_ENV_FILE:-$BEAVER_HOME/runtime.env}"

log() {
  printf '[app-instance] %s\n' "$*"
}

require_file() {
  local path="$1"
  local message="$2"
  if [[ ! -f "$path" ]]; then
    printf '[app-instance] %s: %s\n' "$message" "$path" >&2
    exit 1
  fi
}

cleanup() {
  local status=$?

  if [[ -n "${NGINX_PID:-}" ]]; then
    kill "${NGINX_PID}" 2>/dev/null || true
  fi
  if [[ -n "${FRONTEND_PID:-}" ]]; then
    kill "${FRONTEND_PID}" 2>/dev/null || true
  fi
  if [[ -n "${BACKEND_PID:-}" ]]; then
    kill "${BACKEND_PID}" 2>/dev/null || true
  fi

  wait 2>/dev/null || true
  exit "$status"
}

trap cleanup EXIT INT TERM

mkdir -p "$BEAVER_HOME" "$BEAVER_WORKSPACE"

if [[ -f "$BEAVER_RUNTIME_ENV_FILE" ]]; then
  set -a
  . "$BEAVER_RUNTIME_ENV_FILE"
  set +a
fi

require_file "$BEAVER_CONFIG_PATH" "Missing Beaver config"

export BEAVER_AUTH_FILE
export BEAVER_RUNTIME_ENV_FILE
export BEAVER_HOME
export BEAVER_CONFIG_PATH
export BEAVER_WORKSPACE
export PORT="$APP_FRONTEND_PORT"
export HOSTNAME="127.0.0.1"
export PYTHONFAULTHANDLER="${PYTHONFAULTHANDLER:-1}"

log "starting Beaver backend on 127.0.0.1:${APP_BACKEND_PORT} (loop=${UVICORN_LOOP}, http=${UVICORN_HTTP}, ws=${UVICORN_WS})"
(
  cd /opt/app/backend
  python -m uvicorn "beaver.interfaces.web.app:create_app" --factory --host 127.0.0.1 --port "$APP_BACKEND_PORT" --loop "$UVICORN_LOOP" --http "$UVICORN_HTTP" --ws "$UVICORN_WS"
) &
BACKEND_PID=$!

log "starting frontend on 127.0.0.1:${APP_FRONTEND_PORT}"
(
  cd /opt/app/frontend
  node server.js
) &
FRONTEND_PID=$!

log "starting nginx on 0.0.0.0:${APP_PUBLIC_PORT}"
nginx -c /opt/app/nginx.conf -g 'daemon off;' &
NGINX_PID=$!

wait -n "$BACKEND_PID" "$FRONTEND_PID" "$NGINX_PID"
