#!/bin/bash

# 配置区
APP_NAME="lj360_camera"
WORK_DIR="/home/ztl/LJ360"
PYTHON_SCRIPT="web.py"
USER="ztl"  # 替换为实际用户名（当前是 root，但建议用普通用户）

SYSTEMD_SERVICE_FILE="/etc/systemd/system/${APP_NAME}.service"
SCRIPT_PATH="$WORK_DIR/camera_manager.sh"

# 日志文件（保活日志）
LOG_FILE="$WORK_DIR/${APP_NAME}_keepalive.log"

# 启动主程序（带保活循环）
start_app() {
    cd "$WORK_DIR" || exit 1
    echo "$(date): 启动 $APP_NAME 应用..." >> "$LOG_FILE"
    while true; do
        if python3 "$PYTHON_SCRIPT"; then
            echo "$(date): 程序正常退出，即将重启..." >> "$LOG_FILE"
        else
            echo "$(date): 程序异常退出（代码 $?），5秒后重启..." >> "$LOG_FILE"
        fi
        sleep 5
    done
}

# 创建 systemd 服务文件
create_systemd_service() {
    cat > "$SYSTEMD_SERVICE_FILE" <<EOF
[Unit]
Description=LJ360 Four-Camera BirdView System
After=multi-user.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$WORK_DIR
ExecStart=/bin/bash $SCRIPT_PATH run
Restart=always
RestartSec=5
StandardOutput=append:$LOG_FILE
StandardError=append:$LOG_FILE

[Install]
WantedBy=multi-user.target
EOF

    chmod 644 "$SYSTEMD_SERVICE_FILE"
    systemctl daemon-reload
    echo "✅ systemd 服务已创建: $APP_NAME"
}

# 启用开机自启
enable_autostart() {
    create_systemd_service
    systemctl enable "$APP_NAME".service
    systemctl start "$APP_NAME".service
    echo "✅ 已启用开机自启，并启动服务"
}

# 禁用开机自启
disable_autostart() {
    systemctl stop "$APP_NAME".service 2>/dev/null
    systemctl disable "$APP_NAME".service 2>/dev/null
    rm -f "$SYSTEMD_SERVICE_FILE"
    systemctl daemon-reload
    echo "✅ 已禁用开机自启，并移除服务"
}

# 显示状态
show_status() {
    if systemctl is-active --quiet "$APP_NAME".service; then
        echo "🟢 服务正在运行（开机自启已启用）"
        systemctl status "$APP_NAME".service --no-pager
    elif [ -f "$SYSTEMD_SERVICE_FILE" ]; then
        echo "🟠 服务已安装但未运行"
    else
        echo "🔴 服务未安装（开机自启已关闭）"
    fi
}

# 主菜单
show_menu() {
    echo "========================================"
    echo "   LJ360 摄像头系统管理工具"
    echo "========================================"
    show_status
    echo ""
    echo "请选择操作："
    echo "  1) 启用开机自启并启动服务"
    echo "  2) 禁用开机自启并停止服务"
    echo "  3) 仅手动运行一次（不保活）"
    echo "  4) 查看日志"
    echo "  0) 退出"
    echo -n "请输入编号 (0-4): "
}

# 处理命令行参数（用于 systemd 调用）
if [ "$1" = "run" ]; then
    start_app
    exit 0
fi

# 交互式主程序
while true; do
    show_menu
    read -r choice

    case $choice in
        1)
            enable_autostart
            ;;
        2)
            disable_autostart
            ;;
        3)
            echo "🚀 手动运行一次（Ctrl+C 可退出）..."
            cd "$WORK_DIR" && python3 "$PYTHON_SCRIPT"
            ;;
        4)
            echo "📄 最近日志（最后 20 行）："
            tail -n 20 "$LOG_FILE"
            echo -n "按回车返回菜单..."
            read -r
            ;;
        0)
            echo "退出。"
            exit 0
            ;;
        *)
            echo "❌ 无效选项，请输入 0-4"
            sleep 1
            ;;
    esac
    echo ""
done