#!/usr/bin/env bash
# Purpose: start Open WebUI natively for the private chat service on Track M - bound to
#          127.0.0.1 only, with the same settings compose.yaml gives the container, and the
#          values that matter (CHAT_HOST, WEBUI_SECRET_KEY, first-start admin) read from
#          ~/home-chat/.env so they are written down in exactly one place
# Platform: mac (Track M). Also usable on Linux for a front-end outside Docker.
# Minimum memory: 8 GB
# Assumes: ~/home-chat/.env filled in; a Python 3.11 environment at ~/home-chat/venv with
#          open-webui==0.11.3 installed (two uv commands on the lab page); the Ollama
#          application running and answering on 127.0.0.1:11434; curl on PATH.
#          `open-webui serve` listens on 0.0.0.0 unless told otherwise, which is why this
#          script always passes --host 127.0.0.1.
#
# Usage: bash start-webui-native.sh [--home DIR] [--port N]
#   e.g. bash ~/home-chat/start-webui-native.sh

set -euo pipefail

HOME_CHAT="${HOME}/home-chat"
PORT=8080
OLLAMA_URL="http://127.0.0.1:11434"

usage() { sed -n '2,16p' "$0"; }

while [ $# -gt 0 ]; do
  case "$1" in
    --home) HOME_CHAT="${2:?--home needs a directory}"; shift 2 ;;
    --port) PORT="${2:?--port needs a number}"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done

ENV_FILE="${HOME_CHAT}/.env"
SERVE="${HOME_CHAT}/venv/bin/open-webui"
DATA_DIR="${HOME_CHAT}/webui-data"

die() { echo "$*" >&2; exit 1; }

[ -f "$ENV_FILE" ] || die "No ${ENV_FILE}. Copy env-example.txt there and fill it in (task 2)."
[ -x "$SERVE" ] || die "No ${SERVE}. Create the environment first (task 4, Track M)."
command -v curl >/dev/null 2>&1 || die "curl is not on PATH."

# Read single KEY=value lines without executing the file.
env_value() { sed -n "s/^$1=//p" "$ENV_FILE" | tail -n 1; }

CHAT_HOST="$(env_value CHAT_HOST)"
WEBUI_SECRET_KEY="$(env_value WEBUI_SECRET_KEY)"
WEBUI_ADMIN_EMAIL="$(env_value WEBUI_ADMIN_EMAIL)"
WEBUI_ADMIN_PASSWORD="$(env_value WEBUI_ADMIN_PASSWORD)"
WEBUI_ADMIN_NAME="$(env_value WEBUI_ADMIN_NAME)"

[ -n "$CHAT_HOST" ] || die "CHAT_HOST is empty in ${ENV_FILE}."
[ -n "$WEBUI_SECRET_KEY" ] || die "WEBUI_SECRET_KEY is empty in ${ENV_FILE}; generate it with: openssl rand -hex 32"

curl --silent --fail --max-time 5 "${OLLAMA_URL}/api/version" >/dev/null \
  || die "Ollama is not answering on ${OLLAMA_URL}. Open the Ollama application first."

if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then
  die "Something is already listening on port ${PORT}: $(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN | tail -n +2)"
fi

mkdir -p "$DATA_DIR"
echo "==> Open WebUI on 127.0.0.1:${PORT}, data in ${DATA_DIR}, engine ${OLLAMA_URL}"
if [ -n "$WEBUI_ADMIN_EMAIL" ] && [ -n "$WEBUI_ADMIN_PASSWORD" ]; then
  echo "==> First-start administrator ${WEBUI_ADMIN_EMAIL} will be created if no account exists yet"
fi

exec env \
  DATA_DIR="$DATA_DIR" \
  OLLAMA_BASE_URL="$OLLAMA_URL" \
  ENABLE_OPENAI_API="false" \
  WEBUI_SECRET_KEY="$WEBUI_SECRET_KEY" \
  WEBUI_URL="https://${CHAT_HOST}" \
  CORS_ALLOW_ORIGIN="https://${CHAT_HOST}" \
  ENABLE_SIGNUP="false" \
  DEFAULT_USER_ROLE="pending" \
  WEBUI_ADMIN_EMAIL="$WEBUI_ADMIN_EMAIL" \
  WEBUI_ADMIN_PASSWORD="$WEBUI_ADMIN_PASSWORD" \
  WEBUI_ADMIN_NAME="${WEBUI_ADMIN_NAME:-Admin}" \
  WEBUI_SESSION_COOKIE_SECURE="true" \
  WEBUI_SESSION_COOKIE_SAME_SITE="strict" \
  ENABLE_VERSION_UPDATE_CHECK="false" \
  "$SERVE" serve --host 127.0.0.1 --port "$PORT"
