#!/bin/bash
# 定时任务管理脚本
# 用法：./manage-tasks.sh [status|start|stop|run|edit]

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WEATHER_SCRIPT="$SCRIPT_DIR/weather-daily.sh"
SERVICE_FILE="$HOME/.config/systemd/user/daily-weather.service"
TIMER_FILE="$HOME/.config/systemd/user/daily-weather.timer"

show_status() {
    echo "=== 定时任务状态 ==="
    systemctl --user list-timers --all | grep -E "weather|NEXT|LEFT"
    echo ""
    echo "=== 服务状态 ==="
    systemctl --user status daily-weather.service 2>/dev/null | head -10
    echo ""
    echo "=== 脚本路径 ==="
    echo "天气脚本：$WEATHER_SCRIPT"
    echo "Service:  $SERVICE_FILE"
    echo "Timer:    $TIMER_FILE"
}

run_now() {
    echo "=== 手动运行天气预报 ==="
    bash "$WEATHER_SCRIPT"
}

edit_script() {
    echo "编辑天气脚本：$WEATHER_SCRIPT"
    nano "$WEATHER_SCRIPT"
}

edit_service() {
    echo "编辑 Service 配置：$SERVICE_FILE"
    nano "$SERVICE_FILE"
}

reload() {
    echo "重新加载 systemd 配置..."
    systemctl --user daemon-reload
    systemctl --user restart daily-weather.timer
    echo "✓ 配置已重载"
}

case "$1" in
    status)
        show_status
        ;;
    start)
        systemctl --user enable daily-weather.timer
        systemctl --user start daily-weather.timer
        echo "✓ 定时任务已启动"
        ;;
    stop)
        systemctl --user stop daily-weather.timer
        systemctl --user disable daily-weather.timer
        echo "✓ 定时任务已停止"
        ;;
    run|test)
        run_now
        ;;
    edit)
        edit_script
        ;;
    edit-service)
        edit_service
        ;;
    reload)
        reload
        ;;
    *)
        echo "用法：$0 {status|start|stop|run|edit|edit-service|reload}"
        echo ""
        echo "命令说明:"
        echo "  status      - 查看定时任务状态"
        echo "  start       - 启动定时任务"
        echo "  stop        - 停止定时任务"
        echo "  run/test    - 手动运行一次（测试用）"
        echo "  edit        - 编辑天气脚本（修改 Webhook 等）"
        echo "  edit-service - 编辑 Service 配置（修改执行时间等）"
        echo "  reload      - 重新加载配置"
        ;;
esac
