#!/bin/bash
# XNode SSL Certificate Auto Renewal Cron Installation
# 安装自动续期定时任务

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RENEW_SCRIPT="${SCRIPT_DIR}/cert-renew.sh"
CRON_JOB="0 3 * * * ${RENEW_SCRIPT} >> ${SCRIPT_DIR}/cert-renew.log 2>&1"

show_usage() {
    echo -e "${BLUE}XNode SSL Certificate Auto Renewal Cron Installation${NC}"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo -e "${BLUE}选项:${NC}"
    echo "  --install      安装定时任务（默认）"
    echo "  --uninstall    卸载定时任务"
    echo "  --check         检查定时任务状态"
    echo "  --time TIME     设置执行时间（格式: HH:MM，默认: 03:00）"
    echo "  --help, -h      显示帮助信息"
    echo ""
    echo -e "${BLUE}示例:${NC}"
    echo "  $0 --install              # 安装定时任务（默认每天 03:00）"
    echo "  $0 --install --time 02:30 # 安装定时任务（每天 02:30）"
    echo "  $0 --uninstall            # 卸载定时任务"
    echo "  $0 --check                # 检查定时任务状态"
    echo ""
}

install_cron() {
    local cron_time="${1:-03:00}"
    local hour=$(echo "$cron_time" | cut -d':' -f1)
    local minute=$(echo "$cron_time" | cut -d':' -f2)
    
    # 验证时间格式
    if ! [[ "$hour" =~ ^[0-9]+$ ]] || ! [[ "$minute" =~ ^[0-9]+$ ]] || \
       [ "$hour" -lt 0 ] || [ "$hour" -gt 23 ] || \
       [ "$minute" -lt 0 ] || [ "$minute" -gt 59 ]; then
        echo -e "${RED}错误: 时间格式不正确，请使用 HH:MM 格式${NC}"
        exit 1
    fi
    
    # 检查续期脚本是否存在
    if [ ! -f "$RENEW_SCRIPT" ]; then
        echo -e "${RED}错误: 续期脚本不存在: $RENEW_SCRIPT${NC}"
        exit 1
    fi
    
    # 赋予执行权限
    chmod +x "$RENEW_SCRIPT"
    
    # 创建 cron 任务
    local cron_line="$minute $hour * * * $RENEW_SCRIPT >> ${SCRIPT_DIR}/cert-renew.log 2>&1"
    
    # 检查是否已存在
    if crontab -l 2>/dev/null | grep -q "$RENEW_SCRIPT"; then
        echo -e "${YELLOW}定时任务已存在，更新中...${NC}"
        # 删除旧任务
        crontab -l 2>/dev/null | grep -v "$RENEW_SCRIPT" | crontab -
    fi
    
    # 添加新任务
    (crontab -l 2>/dev/null; echo "$cron_line") | crontab -
    
    echo -e "${GREEN}定时任务安装成功！${NC}"
    echo -e "${BLUE}执行时间: 每天 $cron_time${NC}"
    echo -e "${BLUE}日志文件: ${SCRIPT_DIR}/cert-renew.log${NC}"
    echo ""
    echo -e "${YELLOW}查看定时任务:${NC}"
    echo "  crontab -l"
    echo ""
    echo -e "${YELLOW}查看日志:${NC}"
    echo "  tail -f ${SCRIPT_DIR}/cert-renew.log"
}

uninstall_cron() {
    if crontab -l 2>/dev/null | grep -q "$RENEW_SCRIPT"; then
        crontab -l 2>/dev/null | grep -v "$RENEW_SCRIPT" | crontab -
        echo -e "${GREEN}定时任务已卸载${NC}"
    else
        echo -e "${YELLOW}未找到定时任务${NC}"
    fi
}

check_cron() {
    echo -e "${BLUE}检查定时任务状态...${NC}"
    echo ""
    
    if crontab -l 2>/dev/null | grep -q "$RENEW_SCRIPT"; then
        echo -e "${GREEN}✓ 定时任务已安装${NC}"
        echo ""
        echo -e "${BLUE}当前定时任务:${NC}"
        crontab -l 2>/dev/null | grep "$RENEW_SCRIPT"
        echo ""
        
        # 检查续期脚本权限
        if [ -x "$RENEW_SCRIPT" ]; then
            echo -e "${GREEN}✓ 续期脚本有执行权限${NC}"
        else
            echo -e "${RED}✗ 续期脚本没有执行权限${NC}"
            echo -e "${YELLOW}运行: chmod +x $RENEW_SCRIPT${NC}"
        fi
        
        # 检查日志文件
        if [ -f "${SCRIPT_DIR}/cert-renew.log" ]; then
            echo -e "${GREEN}✓ 日志文件存在${NC}"
            echo -e "${BLUE}最后 10 行日志:${NC}"
            tail -n 10 "${SCRIPT_DIR}/cert-renew.log"
        else
            echo -e "${YELLOW}日志文件不存在（首次运行后会创建）${NC}"
        fi
    else
        echo -e "${RED}✗ 定时任务未安装${NC}"
        echo ""
        echo -e "${YELLOW}安装定时任务:${NC}"
        echo "  $0 --install"
    fi
}

# 解析参数
ACTION="install"
CRON_TIME="03:00"

while [[ $# -gt 0 ]]; do
    case $1 in
        --install)
            ACTION="install"
            shift
            ;;
        --uninstall)
            ACTION="uninstall"
            shift
            ;;
        --check)
            ACTION="check"
            shift
            ;;
        --time)
            CRON_TIME="$2"
            shift 2
            ;;
        --help|-h)
            show_usage
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            show_usage
            exit 1
            ;;
    esac
done

# 执行操作
case $ACTION in
    install)
        install_cron "$CRON_TIME"
        ;;
    uninstall)
        uninstall_cron
        ;;
    check)
        check_cron
        ;;
esac

