#!/bin/bash
# 末日重生-开局囤货十亿物资 - 每5章自动同步脚本

BOOK_DIR="/root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资"
cd "$BOOK_DIR"

# 获取当前章节数
CHAPTERS=$(ls chapters/0*.md 2>/dev/null | wc -l)

# 读取上次同步的章节数
SYNC_FILE=".last_sync"
if [ -f "$SYNC_FILE" ]; then
    LAST_SYNC=$(cat "$SYNC_FILE")
else
    LAST_SYNC=0
fi

# 检查是否新增5章或以上
NEW_CHAPTERS=$((CHAPTERS - LAST_SYNC))

echo "[末日重生] 自动同步检查"
echo "当前章节: $CHAPTERS"
echo "上次同步: $LAST_SYNC"
echo "新增章节: $NEW_CHAPTERS"

if [ "$NEW_CHAPTERS" -ge 5 ] || [ "$1" = "force" ]; then
    if [ "$1" = "force" ]; then
        echo "强制同步模式..."
    else
        echo "检测到新增 $NEW_CHAPTERS 章，执行同步..."
    fi
    
    # 添加更改
    git add chapters/ story/*.md book.json README.md .gitignore auto_sync.sh 2>/dev/null
    
    # 检查是否有更改要提交
    if ! git diff --cached --quiet; then
        # 提交
        git commit -m "自动同步：第${CHAPTERS}章完成 (新增${NEW_CHAPTERS}章)"
        
        # 推送
        git push origin master
        
        # 更新同步记录
        echo "$CHAPTERS" > "$SYNC_FILE"
        
        echo "✅ 同步完成！"
        echo "远程仓库: https://gitea.nevadalice.top:226/liyuchen/novel-doomsday-resurgence"
    else
        echo "没有文件更改需要提交"
    fi
else
    echo "未达到5章，跳过同步 (还需 $((5 - NEW_CHAPTERS)) 章)"
    echo "如需强制同步，请执行: ./auto_sync.sh force"
fi
