#!/bin/bash

# 文件监控脚本
# 实时监控目录变化，触发同步

PROJECT_DIR="/Users/chufeng/.openclaw/sanguo_projects/sanguo_quant_live"
LOG_FILE="$PROJECT_DIR/file-watcher.log"
SYNC_SCRIPT="$PROJECT_DIR/auto-sync.sh"
LOCK_FILE="/tmp/sanguo_sync.lock"

# 确保脚本有执行权限
chmod +x "$SYNC_SCRIPT"

echo "[$(date)] Starting file watcher in $PROJECT_DIR" >> "$LOG_FILE"
echo "[$(date)] Watching for file changes..." >> "$LOG_FILE"

# 创建一个函数来执行同步
run_sync() {
    # 检查锁文件，防止重复运行
    if [ -f "$LOCK_FILE" ]; then
        echo "[$(date)] Sync already in progress, skipping..." >> "$LOG_FILE"
        return 0
    fi
    
    # 创建锁文件
    touch "$LOCK_FILE"
    
    echo "[$(date)] Detected file change, running sync..." >> "$LOG_FILE"
    
    # 执行同步脚本
    "$SYNC_SCRIPT"
    sync_result=$?
    
    if [ $sync_result -eq 0 ]; then
        echo "[$(date)] Sync completed successfully" >> "$LOG_FILE"
    else
        echo "[$(date)] Sync failed with code $sync_result" >> "$LOG_FILE"
    fi
    
    # 删除锁文件
    rm -f "$LOCK_FILE"
}

# 使用fswatch监控文件变化
# fswatch是一个跨平台的文件系统监控工具
# 如果没有安装fswatch，使用inotifywait或find命令替代

# 检查fswatch是否可用
if command -v fswatch &> /dev/null; then
    echo "[$(date)] Using fswatch for file monitoring" >> "$LOG_FILE"
    # fswatch: -e 排除.git目录，-r 递归，-0 输出null分隔符
    fswatch -e "\.git" -e "\.log$" -r -0 "$PROJECT_DIR" | while read -d "" event
    do
        # 过滤掉一些不必要的文件类型
        if [[ ! "$event" =~ \.log$ ]] && [[ ! "$event" =~ \.tmp$ ]] && [[ ! "$event" =~ ~$ ]]; then
            run_sync
            # 添加1秒延迟避免频繁触发
            sleep 1
        fi
    done
elif command -v inotifywait &> /dev/null; then
    echo "[$(date)] Using inotifywait for file monitoring" >> "$LOG_FILE"
    # inotifywait: -r 递归，-m 持续监控，-e 事件类型
    inotifywait -r -m -e create,modify,delete,move "$PROJECT_DIR" --exclude "\.git" --format "%w%f" | while read path
    do
        # 过滤掉日志文件
        if [[ ! "$path" =~ \.log$ ]] && [[ ! "$path" =~ \.tmp$ ]] && [[ ! "$path" =~ ~$ ]]; then
            run_sync
            # 添加1秒延迟避免频繁触发
            sleep 1
        fi
    done
else
    echo "[$(date)] WARNING: fswatch and inotifywait not found, falling back to find polling" >> "$LOG_FILE"
    echo "[$(date)] This is less efficient but will work" >> "$LOG_FILE"
    
    # 使用find命令进行轮询（每5秒检查一次）
    last_check_time=$(date +%s)
    
    while true; do
        current_time=$(date +%s)
        
        # 检查是否有文件在最近5秒内被修改
        # find命令查找最近修改的文件
        changed_files=$(find "$PROJECT_DIR" -type f ! -name "*.log" ! -name "*.tmp" ! -name "*~" ! -path "*/.git/*" -mtime -5s 2>/dev/null | head -10)
        
        if [ -n "$changed_files" ]; then
            # 有文件变化，执行同步
            run_sync
        fi
        
        # 等待5秒
        sleep 5
    done
fi