#!/bin/bash

LOG_FILE="${TRIM_PKGVAR}/info.log"
PID_FILE="${TRIM_PKGVAR}/app.pid"
APP_PORT=8787

# write the command to start your program here
CMD="cd /var/apps/AipaiNet/target/server && HOME='${TRIM_PKGVAR}' ./aipai web --port ${APP_PORT}"

log_msg() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> ${LOG_FILE}
}

# 飞牛默认防火墙策略是 DROP，只放行明确允许的端口，
# 不放行的话应用装好了但外面打不开（面板显示“无法访问”）。
ensure_port_open() {
    command -v ufw >/dev/null 2>&1 || return 0
    ufw status 2>/dev/null | grep -q "^Status: active" || return 0
    if ! ufw status 2>/dev/null | grep -qE "^${APP_PORT}/tcp"; then
        ufw allow ${APP_PORT}/tcp >/dev/null 2>&1 && log_msg "已放行端口 ${APP_PORT}/tcp"
    fi
    # 直接写 iptables 兜底（ufw 规则没生效时）
    if ! iptables -S 2>/dev/null | grep -q -- "--dport ${APP_PORT} -j ACCEPT"; then
        iptables -I ufw-user-input -p tcp --dport ${APP_PORT} -j ACCEPT >/dev/null 2>&1
    fi
    return 0
}

start_process() {
    if status; then
        return 0
    fi

    log_msg "Starting process ..."
    ensure_port_open
    # run cmd to start process
    bash -c "${CMD}" >> ${LOG_FILE} 2>&1 &
    # write pid to pidfile
    printf "%s" "$!" > ${PID_FILE}
    return 0
}

stop_process() {
    log_msg "Stopping process ..."

    if [ -r "${PID_FILE}" ]; then
        pid=$(head -n 1 "${PID_FILE}" | tr -d '[:space:]')

        log_msg "pid=${pid}"
        if ! check_process "${pid}"; then
            rm -f "${PID_FILE}"
            log_msg "remove pid file 1"
            return
        fi

        log_msg "send TERM signal to PID:${pid}..."
        kill -TERM ${pid} >> ${LOG_FILE} 2>&1

        local count=0
        while check_process "${pid}" && [ $count -lt 10 ]; do
            sleep 1
            count=$((count + 1))
            log_msg "waiting process terminal... (${count}s/10s)"
        done

        if check_process "${pid}"; then
            log_msg "send KILL signal to PID:${pid}..."
            kill -KILL "${pid}"
            sleep 1
            rm -f "${PID_FILE}"
        else
            log_msg "process killed... "
        fi
    fi

    return 0
}

check_process() {
    local pid=$1
    if kill -0 "${pid}" 2>/dev/null; then
        return 0  # process exist
    else
        return 1  # process not exist
    fi
}

status() {
    if [ -f "${PID_FILE}" ]; then
        pid=$(head -n 1 "${PID_FILE}" | tr -d '[:space:]')
        if check_process "${pid}"; then
            return 0
        else
            rm -f "${PID_FILE}"
        fi
    fi

    return 1
}

case $1 in
start)
    start_process
    ;;
stop)
    stop_process
    ;;
status)
    if status; then
        exit 0
    else
        exit 3
    fi
    ;;
*)
    exit 1
    ;;
esac
