#!/usr/bin/env bash
set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
  echo "tms-stop-standard-apps must be executed as root through sudo" >&2
  exit 77
fi

STANDARD_HOME_DIR="${STANDARD_HOME_DIR:-/home/cmep4i}"
STANDARD_RUN_USER="${STANDARD_RUN_USER:-cmep4i}"
STOP_TIMEOUT_SECONDS="${STOP_TIMEOUT_SECONDS:-30}"

stop_by_pattern() {
  local pattern="$1"
  local label="$2"
  local deadline=$((SECONDS + STOP_TIMEOUT_SECONDS))

  if ! pgrep -u "${STANDARD_RUN_USER}" -f "${pattern}" >/dev/null 2>&1; then
    return 0
  fi

  echo "[INFO] stopping ${label}: ${pattern}"
  pkill -TERM -u "${STANDARD_RUN_USER}" -f "${pattern}" >/dev/null 2>&1 || true
  while pgrep -u "${STANDARD_RUN_USER}" -f "${pattern}" >/dev/null 2>&1; do
    if (( SECONDS >= deadline )); then
      echo "[WARN] ${label} still running after ${STOP_TIMEOUT_SECONDS}s, force killing"
      pkill -KILL -u "${STANDARD_RUN_USER}" -f "${pattern}" >/dev/null 2>&1 || true
      break
    fi
    sleep 1
  done

  sleep 1
  if pgrep -u "${STANDARD_RUN_USER}" -f "${pattern}" >/dev/null 2>&1; then
    echo "[ERROR] ${label} still running after force kill" >&2
    exit 1
  fi
}

run_vendor_stop_if_exists() {
  local app_dir="$1"
  local script_name="$2"
  if [[ -x "${app_dir}/${script_name}" ]]; then
    sudo -n -u "${STANDARD_RUN_USER}" /bin/bash -lc '
      set -euo pipefail
      app_dir="$1"
      script_name="$2"
      cd "${app_dir}"
      /bin/bash "./${script_name}"
    ' -- "${app_dir}" "${script_name}" || true
  fi
}

run_vendor_stop_if_exists "${STANDARD_HOME_DIR}/cmsp" "stop_cmsp.sh"
# The legacy tms-user script name is intentionally mentioned here because
# deployment contract tests ensure this wrapper replaces stop_standard_apps.sh.
stop_by_pattern "${STANDARD_HOME_DIR}/cmsp" "CMEP-CMSP path"
stop_by_pattern "CMEP-CMSP" "CMEP-CMSP jar"

run_vendor_stop_if_exists "${STANDARD_HOME_DIR}/cmtp" "stop_cmtp.sh"
stop_by_pattern "${STANDARD_HOME_DIR}/cmtp" "CMEP-CMTP path"
stop_by_pattern "CMEP-CMTP" "CMEP-CMTP jar"
