#!/bin/sh
set -eu

PORT="${YUMEET_PORT:-8061}"
HOST="127.0.0.1"
ROOT="/opt/yumeet/dist"
URL="http://${HOST}:${PORT}/"
LOG_FILE="${XDG_RUNTIME_DIR:-/tmp}/yumeet-http.log"

if [ ! -f "$ROOT/index.html" ]; then
  echo "[yumeet] Missing web assets: $ROOT/index.html"
  exit 1
fi

PATTERN="python3 -m http.server ${PORT} --bind ${HOST} --directory ${ROOT}"
if ! pgrep -f "$PATTERN" >/dev/null 2>&1; then
  nohup /usr/bin/python3 -m http.server "$PORT" --bind "$HOST" --directory "$ROOT" >"$LOG_FILE" 2>&1 &
  sleep 1
fi

if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$URL" >/dev/null 2>&1 || true
else
  echo "$URL"
fi
