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

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

pid=""
IFS= read -r pid < "$PID_FILE" || true
if [ -z "$pid" ]; then
  "$RM" -f "$PID_FILE"
  echo "mailcat 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 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 still running after SIGKILL: $pid"
      exit 1
    fi
  fi
fi
"$RM" -f "$PID_FILE"
echo "mailcat stopped"
