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

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
RUN_DIR="$ROOT_DIR/run"
API_PID_FILE="$RUN_DIR/api.pid"
WORKER_PID_FILE="$RUN_DIR/worker.pid"
HTTP_PORT=16811
WORKER_HTTP_PORT=16812

load_env_config() {
  local env_file

  for env_file in ".env"; do
    if [[ -f "$ROOT_DIR/$env_file" ]]; then
      # shellcheck disable=SC1090
      source "$ROOT_DIR/$env_file"
    fi
  done

  if [[ -n "${APP_ENV:-}" && -f "$ROOT_DIR/.env.$APP_ENV" ]]; then
    # shellcheck disable=SC1090
    source "$ROOT_DIR/.env.$APP_ENV"
  elif [[ -n "${GO_ENV:-}" && -f "$ROOT_DIR/.env.$GO_ENV" ]]; then
    # shellcheck disable=SC1090
    source "$ROOT_DIR/.env.$GO_ENV"
  elif [[ -n "${ENV:-}" && -f "$ROOT_DIR/.env.$ENV" ]]; then
    # shellcheck disable=SC1090
    source "$ROOT_DIR/.env.$ENV"
  fi

  if [[ -f "$ROOT_DIR/.env.local" ]]; then
    # shellcheck disable=SC1090
    source "$ROOT_DIR/.env.local"
  fi
}

port_pid() {
  local port="$1"
  lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | head -n 1 || true
}

stop_port_process() {
  local name="$1"
  local port="$2"
  local pid

  pid="$(port_pid "$port")"
  if [[ -z "$pid" ]]; then
    return 0
  fi

  kill "$pid" 2>/dev/null || true
  echo "$name stopped by port, pid=$pid"
}

stop_process() {
  local name="$1"
  local pid_file="$2"

  if [[ ! -f "$pid_file" ]]; then
    echo "$name is not running"
    return 0
  fi

  local pid
  pid="$(cat "$pid_file")"
  if [[ -z "$pid" ]]; then
    rm -f "$pid_file"
    echo "$name pid file is empty, cleaned"
    return 0
  fi

  if kill -0 "$pid" 2>/dev/null; then
    kill "$pid"
    echo "$name stopped, pid=$pid"
  else
    echo "$name is not running, stale pid=$pid"
  fi

  rm -f "$pid_file"
}

stop_process "worker" "$WORKER_PID_FILE"
stop_process "api" "$API_PID_FILE"
load_env_config
stop_port_process "worker" "${WORKER_HTTP_PORT}"
stop_port_process "api" "${HTTP_PORT}"
