#!/bin/bash
set -u

CONFIG_FILE="${SEEKDB_CONFIG_FILE:-/opt/seekdb/etc/seekdb/seekdb.cnf}"
BASE_DIR="/opt/seekdb/var/seekdb/data"
ACTIVE_PATHS_FILE="/opt/seekdb/var/seekdb/run/active_paths"
TIMEOUT="${SEEKDB_STOP_TIMEOUT:-30}"

trim() {
  local value="$*"
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%"${value##*[![:space:]]}"}"
  printf "%s" "$value"
}

read_base_dir() {
  if read_key_value "$ACTIVE_PATHS_FILE" "base-dir"; then
    return 0
  fi
  read_key_value "$CONFIG_FILE" "base-dir" || true
}

read_key_value() {
  local file="$1"
  local wanted="$2"
  [ -f "$file" ] || return 1
  while IFS= read -r line || [ -n "$line" ]; do
    line="$(trim "$line")"
    [ -z "$line" ] && continue
    case "$line" in
      \#*|\;*) continue ;;
    esac
    key="$(trim "${line%%=*}")"
    value="$(trim "${line#*=}")"
    if [ "$key" = "$wanted" ]; then
      case "$wanted" in
        base-dir) BASE_DIR="$value" ;;
      esac
      return 0
    fi
  done < "$file"
  return 1
}

is_alive() {
  local pid="$1"
  [ -n "$pid" ] || return 1
  ps -p "$pid" >/dev/null 2>&1
}

stop_pid_file() {
  local pid_file="$1"
  [ -f "$pid_file" ] || return 0

  local pid
  pid="$(cat "$pid_file" 2>/dev/null || true)"
  is_alive "$pid" || return 0

  # Guard against PID recycling: verify the process executable is under /opt/seekdb/
  local proc_cmd
  proc_cmd="$(ps -p "$pid" -ww -o args= 2>/dev/null | head -1 || true)"
  case "$proc_cmd" in
    /opt/seekdb/*)  ;;
    *)
      echo "Skipping PID $pid from $pid_file: not a seekdb process (stale PID file)"
      rm -f "$pid_file" 2>/dev/null || true
      return 0
      ;;
  esac

  echo "Stopping process $pid from $pid_file"
  kill "$pid" 2>/dev/null || true

  local elapsed=0
  while is_alive "$pid" && [ "$elapsed" -lt "$TIMEOUT" ]; do
    sleep 1
    elapsed=$((elapsed + 1))
  done

  if is_alive "$pid"; then
    echo "Process $pid did not stop within ${TIMEOUT}s, forcing shutdown"
    kill -9 "$pid" 2>/dev/null || true
  fi
}

read_base_dir

stop_pid_file "$BASE_DIR/run/obshell.pid"
stop_pid_file "$BASE_DIR/run/daemon.pid"
stop_pid_file "$BASE_DIR/run/seekdb.pid"
rm -f "$ACTIVE_PATHS_FILE" 2>/dev/null || true
