#!/bin/sh /etc/rc.common
# OpenWrt 启动脚本
# 文件位置: /etc/init.d/drcom-login

START=99
STOP=15
USE_PROCD=1

# 程序路径
PROG="/usr/bin/drcom_login.py"
CONFIG="/etc/drcom/config.json"
PIDFILE="/var/run/drcom-login.pid"
LOGFILE="/var/log/drcom-login.log"

# 检查 Python 和依赖
check_dependencies() {
    if ! command -v python3 >/dev/null 2>&1; then
        echo "[ERROR] python3 not found. Please install it first."
        return 1
    fi

    python3 -c "import requests" 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "[ERROR] Python 'requests' module not found."
        echo "Run: opkg install python3-requests"
        return 1
    fi
}

# 启动服务
start_service() {
    echo "[START] Starting DRCom Login Service..."

    check_dependencies || return 1

    # 检查配置文件
    if [ ! -f "$CONFIG" ]; then
        echo "[ERROR] Config file not found: $CONFIG"
        echo "Please run: /etc/drcom/install.sh"
        return 1
    fi

    # 检查主程序
    if [ ! -f "$PROG" ]; then
        echo "[ERROR] Program not found: $PROG"
        return 1
    fi

    # 启动程序
    procd_open_instance
    procd_set_param command python3 "$PROG" "$CONFIG"
    procd_set_param pidfile "$PIDFILE"
    procd_set_param stdout "$LOGFILE"
    procd_set_param stderr "$LOGFILE"
    procd_set_param respawn ${respawn_threshold:-60} ${respawn_timeout:-5} ${respawn_retry:-5}
    procd_close_instance

    echo "[OK] DRCom Login Service started."
}

# 停止服务
stop_service() {
    echo "[STOP] Stopping DRCom Login Service..."
    rm -f "$PIDFILE"
}

# 重启服务
restart() {
    stop_service
    sleep 2
    start_service
}

# 查看状态
status() {
    if [ -f "$PIDFILE" ]; then
        pid=$(cat "$PIDFILE")
        if kill -0 "$pid" 2>/dev/null; then
            echo "[STATUS] DRCom Login Service is running (PID: $pid)"
            return 0
        else
            echo "[STATUS] PID file exists but process not running"
            rm -f "$PIDFILE"
            return 1
        fi
    else
        echo "[STATUS] DRCom Login Service is not running"
        return 1
    fi
}

# 查看日志
show_log() {
    if [ -f "$LOGFILE" ]; then
        tail -n 50 "$LOGFILE"
    else
        echo "[INFO] Log file not found: $LOGFILE"
    fi
}
