#!/bin/bash
# uninstall_init：卸载**之前**执行（应用文件尚未移除）。
#
# 停掉服务，避免卸载过程中进程还占着 socket 与数据库。
set -uo pipefail

TP_HOOK=uninstall_init
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
. "$SELF_DIR/lib.sh"

tp_dump_env uninstall_init
tp_log uninstall_init "卸载前停止服务"

pid_file="${TRIM_PKGVAR:-}/app.pid"
if [ -n "${TRIM_PKGVAR:-}" ] && [ -f "$pid_file" ]; then
    pid="$(head -n 1 "$pid_file" 2>/dev/null | tr -d '[:space:]')"
    if [ -n "$pid" ] && tp_pid_is_ours "$pid"; then
        tp_log uninstall_init "发送 TERM 给 pid=$pid"
        kill -TERM "$pid" 2>/dev/null
        waited=0
        while tp_pid_is_ours "$pid" && [ "$waited" -lt 15 ]; do
            sleep 1
            waited=$((waited + 1))
        done
        if tp_pid_is_ours "$pid"; then
            tp_log uninstall_init "超时未退出，发送 KILL"
            kill -KILL "$pid" 2>/dev/null
        fi
    fi
    rm -f "$pid_file" 2>/dev/null
fi

tp_log uninstall_init "服务已停止"
exit 0
