#!/bin/sh
set -eu
WEB_PID_FILE="/share/homes/mailcat/mailcat/run/mailcat_web.pid"
RM="/bin/rm"

if [ ! -f "$WEB_PID_FILE" ]; then
  echo "mailcat web not running: no pid file"
  exit 0
fi

pid=""
IFS= read -r pid < "$WEB_PID_FILE" || true
if [ -z "$pid" ]; then
  "$RM" -f "$WEB_PID_FILE"
  echo "mailcat web not running: empty pid file removed"
  exit 0
fi

if kill -0 "$pid" 2>/dev/null; then
  kill "$pid"
  timeout=20
  while [ "$timeout" -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
    sleep 1
    timeout=$((timeout - 1))
  done
  if kill -0 "$pid" 2>/dev/null; then
    echo "mailcat web still running after SIGTERM, sending SIGKILL: $pid"
    kill -KILL "$pid" 2>/dev/null || true
    timeout=5
    while [ "$timeout" -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
      sleep 1
      timeout=$((timeout - 1))
    done
    if kill -0 "$pid" 2>/dev/null; then
      echo "mailcat web still running after SIGKILL: $pid"
      exit 1
    fi
  fi
fi
"$RM" -f "$WEB_PID_FILE"
echo "mailcat web stopped"
