#!/bin/sh
set -eu
APP_DIR="/share/homes/mailcat/mailcat"
PYTHON="/opt/bin/python3"
LOG_DIR="/share/homes/mailcat/mailcat/log"
RUN_DIR="/share/homes/mailcat/mailcat/run"
WEB_PID_FILE="/share/homes/mailcat/mailcat/run/mailcat_web.pid"
WEB_HOST="0.0.0.0"
WEB_PORT="4321"
WEB_CONFIG="/share/homes/mailcat/mailcat/web_config.json"
MKDIR="/bin/mkdir"

if [ ! -f "$WEB_CONFIG" ]; then
  echo "missing web config: $WEB_CONFIG"
  exit 1
fi

"$MKDIR" -p "$LOG_DIR" "$RUN_DIR"
if [ -f "$WEB_PID_FILE" ]; then
  old_pid=""
  IFS= read -r old_pid < "$WEB_PID_FILE" || true
  if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then
    echo "mailcat web already running: $old_pid"
    exit 0
  fi
fi

cd "$APP_DIR"
"$PYTHON" "$APP_DIR/manage_routes_web.py" --host "$WEB_HOST" --port "$WEB_PORT" --config "$WEB_CONFIG" >> "$LOG_DIR/web.out" 2>&1 &
pid="$!"
echo "$pid" > "$WEB_PID_FILE"
echo "mailcat web started: $pid"
