#!/bin/bash
# 管理 soga 定时重启任务的脚本
# 1 = 设置定时重启
# 2 = 取消定时重启

SERVICE_FILE="/etc/systemd/system/soga-restart.service"
TIMER_FILE="/etc/systemd/system/soga-restart.timer"

show_menu() {
    echo "=============================="
    echo "   soga 定时重启管理脚本"
    echo "=============================="
    echo "1) 设置每天凌晨 2 点自动重启 soga"
    echo "2) 取消定时重启"
    echo "=============================="
    read -p "请输入选项 [1-2]: " choice
}

setup_timer() {
    echo "[INFO] 创建 systemd service..."
    cat > $SERVICE_FILE <<EOF
[Unit]
Description=Restart soga service

[Service]
Type=oneshot
ExecStart=/bin/systemctl restart soga
EOF

    echo "[INFO] 创建 systemd timer..."
    cat > $TIMER_FILE <<EOF
[Unit]
Description=Restart soga service at 2AM daily

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF

    systemctl daemon-reload
    systemctl enable --now soga-restart.timer

    echo "[SUCCESS] 定时任务已启用，每天 2 点重启 soga"
    systemctl list-timers | grep soga-restart
}

remove_timer() {
    systemctl disable --now soga-restart.timer 2>/dev/null
    rm -f $SERVICE_FILE $TIMER_FILE
    systemctl daemon-reload

    echo "[SUCCESS] 定时任务已取消并清理"
}

# 主程序
show_menu

case "$choice" in
    1)
        setup_timer
        ;;
    2)
        remove_timer
        ;;
    *)
        echo "[ERROR] 无效选项"
        ;;
esac
