#!/bin/bash
# Hugo 文件监控守护进程
# 监控 Obsidian 内容目录，自动重新编译

HUGO_DIR="/home/zhn/.openclaw/workspace/skills/robdaily/deploy"
CONTENT_DIR="/home/zhn/.openclaw/workspace/skills/robdaily/site/content"
LOG_FILE="/tmp/hugo-watch.log"
LOCK_FILE="/tmp/hugo-rebuild.lock"

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

rebuild() {
  # 防抖：如果 30 秒内已执行过，跳过
  if [ -f "$LOCK_FILE" ]; then
    last_run=$(stat -c %Y "$LOCK_FILE" 2>/dev/null || echo 0)
    current_time=$(date +%s)
    if [ $((current_time - last_run)) -lt 30 ]; then
      return
    fi
  fi
  
  log "开始重新编译 Hugo..."
  cd "$HUGO_DIR"
  docker compose exec -T hugo-personal-site hugo --minify 2>&1 | tail -5 >> "$LOG_FILE"
  touch "$LOCK_FILE"
  log "Hugo 重新编译完成"
}

# 监听内容目录
log "开始监控：$CONTENT_DIR"
inotifywait -m -r -e modify -e create -e delete --exclude '\.swp$' "$CONTENT_DIR" |
while read -r directory event filename; do
  log "文件变化：$event $filename"
  rebuild
done
