#!/bin/sh

CONF_DIR="/app/conf"
DEFAULT_LUCKY="/app/lucky"
NEW_LUCKY_PATH="$CONF_DIR/bin/lucky"
NEW_LUCKY_TMP="$CONF_DIR/bin/lucky.tmp"

# 信号处理标志
SHUTDOWN_REQUESTED=0
LUCKY_PID=0

# 可中断的 sleep 函数
# 使用后台 sleep + wait 模式，确保信号可以中断等待
interruptible_sleep() {
    sleep "$1" &
    wait $!
}

# 信号处理函数
handle_signal() {
    echo "Received shutdown signal, stopping..."
    SHUTDOWN_REQUESTED=1
    
    # 如果 lucky 进程正在运行，发送信号给它
    if [ $LUCKY_PID -ne 0 ] && kill -0 $LUCKY_PID 2>/dev/null; then
        echo "Sending SIGTERM to lucky process (PID: $LUCKY_PID)"
        kill -TERM $LUCKY_PID 2>/dev/null
        
        # 等待进程退出，最多等待 30 秒
        wait_count=0
        while kill -0 $LUCKY_PID 2>/dev/null && [ $wait_count -lt 30 ]; do
            sleep 1
            wait_count=$((wait_count + 1))
        done
        
        # 如果进程仍在运行，强制终止
        if kill -0 $LUCKY_PID 2>/dev/null; then
            echo "Force killing lucky process"
            kill -9 $LUCKY_PID 2>/dev/null
        fi
    fi
    
    echo "Shutdown complete"
    exit 0
}

# 注册信号处理
trap 'handle_signal' TERM INT QUIT HUP

# 获取 lucky 文件的编译时间戳
# 返回格式: 20250616230405 (便于比较)
get_build_timestamp() {
    lucky_path="$1"
    if [ ! -x "$lucky_path" ]; then
        echo "0"
        return
    fi
    
    # 执行 -info 获取 JSON，提取 Date 字段
    info=$($lucky_path -info 2>/dev/null)
    if [ -z "$info" ]; then
        echo "0"
        return
    fi
    
    # 提取 Date 字段: "Date":"2025-06-16 23:04:05"
    date_str=$(echo "$info" | sed -n 's/.*"Date":"\([^"]*\)".*/\1/p')
    if [ -z "$date_str" ]; then
        echo "0"
        return
    fi
    
    # 转换为可比较的数字格式: 2025-06-16 23:04:05 -> 20250616230405
    timestamp=$(echo "$date_str" | sed 's/[-: ]//g')
    echo "$timestamp"
}

get_lucky_path() {
    # 检查是否有新上传的 tmp 文件
    if [ -f "$NEW_LUCKY_TMP" ]; then
        rm -f "$NEW_LUCKY_PATH"
        mv "$NEW_LUCKY_TMP" "$NEW_LUCKY_PATH"
        chmod 755 "$NEW_LUCKY_PATH"
    fi

    # 获取默认版本的编译时间
    default_ts=$(get_build_timestamp "$DEFAULT_LUCKY")
    echo "Default lucky build timestamp: $default_ts" >&2
    
    # 检查新版本是否存在
    if [ -x "$NEW_LUCKY_PATH" ]; then
        new_ts=$(get_build_timestamp "$NEW_LUCKY_PATH")
        echo "New lucky build timestamp: $new_ts" >&2
        
        # 比较时间戳，使用较新的版本
        if [ "$new_ts" -gt "$default_ts" ] 2>/dev/null; then
            echo "Using newer version from: $NEW_LUCKY_PATH" >&2
            echo "$NEW_LUCKY_PATH"
            return
        else
            echo "Default version is newer or equal" >&2
        fi
    fi

    echo "$DEFAULT_LUCKY"
}

# 检查 lucky 进程是否正在运行
is_lucky_running() {
    # 使用 ps + grep 检查进程，兼容性更好
    ps aux 2>/dev/null | grep -v grep | grep -q "lucky.*-runInDocker" && return 0
    return 1
}

# 主循环
echo "Lucky Docker Start Script"
echo "Checking /app/lucky exists: $(ls -la /app/lucky 2>&1)"

while true; do
    # 检查进程是否已经在运行
    if is_lucky_running; then
        #echo "Lucky process is already running, waiting..."
        interruptible_sleep 5
        [ $SHUTDOWN_REQUESTED -eq 1 ] && exit 0
        continue
    fi

    LUCKY_PATH=$(get_lucky_path)
    echo "Starting Lucky from: $LUCKY_PATH"
    
    # 检查文件是否存在且可执行
    if [ ! -f "$LUCKY_PATH" ]; then
        echo "Error: $LUCKY_PATH not found!"
        sleep 3
        continue
    fi
    
    # 启动 lucky 并记录 PID
    "$LUCKY_PATH" -c "$CONF_DIR/lucky.conf" -runInDocker &
    LUCKY_PID=$!
    echo "Lucky started with PID: $LUCKY_PID"
    
    # 等待进程结束
    wait $LUCKY_PID
    exit_code=$?
    LUCKY_PID=0
    
    # 检查是否收到退出信号
    if [ $SHUTDOWN_REQUESTED -eq 1 ]; then
        echo "Shutdown requested, exiting..."
        exit 0
    fi
    
    echo "Process exited with code $exit_code, restarting in 3 seconds..."
    interruptible_sleep 3
    [ $SHUTDOWN_REQUESTED -eq 1 ] && exit 0
done
