#!/usr/bin/env bash
# 开发期热重载：监听代码目录变化，自动重启 workerman:serve。
# 优先用 fswatch（brew install fswatch），未安装时回退纯 PHP 轮询。
# 用法：php artisan dev:watch  或  bash scripts/dev-watch.sh
set -euo pipefail
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

WATCH_DIRS=(app plugins routes config)
WATCH_FILES=(.env)
WATCH_PATTERN='\.(php|json)$'

restart() {
    echo "[$(date +%H:%M:%S)] 检测到代码变更，重启 workerman:serve..."
    php artisan workerman:serve restart
}

if command -v fswatch >/dev/null 2>&1; then
    echo "使用 fswatch 监听：${WATCH_DIRS[*]} ${WATCH_FILES[*]}（Ctrl+C 退出）"
    args=()
    for d in "${WATCH_DIRS[@]}"; do [ -d "$d" ] && args+=("$d"); done
    for f in "${WATCH_FILES[@]}"; do [ -f "$f" ] && args+=("$f"); done
    fswatch -0 -l 1 -r --include "$WATCH_PATTERN" --exclude '.*' "${args[@]}" \
        | while IFS= read -r -d '' _; do restart; done
else
    echo "未安装 fswatch（brew install fswatch 可升级体验），使用 PHP 轮询兜底..."
    php scripts/dev-watch.php
fi
