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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PID_DIR="$ROOT_DIR/.pids"
LAUNCHD_DOMAIN="gui/$(id -u)"

stop_launchd_label() {
  local label="$1"
  if launchctl bootout "$LAUNCHD_DOMAIN/$label" >/dev/null 2>&1; then
    echo "$label stopped"
  else
    echo "$label not loaded"
  fi
}

stop_pid_file() {
  local name="$1"
  local file="$PID_DIR/$name.pid"
  if [[ ! -f "$file" ]]; then
    echo "$name pid file not found"
    return
  fi
  local pid
  pid="$(cat "$file")"
  if [[ -n "$pid" ]] && kill -0 "$pid" >/dev/null 2>&1; then
    kill -TERM "$pid"
    echo "$name stopped: $pid"
  else
    echo "$name already stopped"
  fi
  rm -f "$file"
}

stop_pid_file api
stop_pid_file web
stop_launchd_label com.skg.tk-recreate.api.dev
stop_launchd_label com.skg.tk-recreate.web.dev
