#!/usr/bin/env bash
set -euo pipefail

# 切换到博客根目录，确保从任何位置执行都能正常工作
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

# 允许用环境变量覆盖默认值
PORT="${PORT:-4000}"
HOST="${HOST:-127.0.0.1}"
BRANCH="${BRANCH:-main}"

usage() {
  cat <<'EOF'
博客脚本用法：
  ./tools/blog.sh clean    # 清理缓存和 public 目录
  ./tools/blog.sh build    # 生成静态文件
  ./tools/blog.sh server   # 启动本地服务
  ./tools/blog.sh preview  # 清理 + 生成 + 启动预览
  ./tools/blog.sh deploy   # 清理 + 生成 + git 提交 + 推送

可选环境变量：
  PORT=4000         预览端口
  HOST=127.0.0.1    监听地址
  BRANCH=main       推送分支
EOF
}

hexo_run() {
  # 把参数原样传给 hexo
  npx hexo "$@"
}

add_blog_files() {
  # 只暂存博客相关文件，避免误把 node_modules、public 或其他杂项提交进去
  local paths=(
    "_config.yml"
    "_config.butterfly.yml"
    "_config.landscape.yml"
    "package.json"
    "package-lock.json"
    "scaffolds"
    "source"
    "themes"
    "tools"
  )

  local existing=()
  local path
  for path in "${paths[@]}"; do
    if [[ -e "$path" ]]; then
      existing+=("$path")
    fi
  done

  if [[ ${#existing[@]} -eq 0 ]]; then
    echo '[deploy] 没有找到可暂存的博客文件' >&2
    exit 1
  fi

  git add -- "${existing[@]}"
}

case "${1:-help}" in
  clean)
    echo '[clean] 清理生成缓存'
    hexo_run clean
    ;;
  build)
    echo '[build] 生成静态文件'
    hexo_run generate
    ;;
  server)
    echo "[server] 启动预览服务：http://${HOST}:${PORT}"
    hexo_run server -i "$HOST" -p "$PORT"
    ;;
  preview)
    echo '[preview] 清理并生成静态文件'
    hexo_run clean
    hexo_run generate

    echo "[preview] 启动预览服务：http://${HOST}:${PORT}"
    hexo_run server -i "$HOST" -p "$PORT"
    ;;
  deploy)
    echo '[deploy] 清理并生成静态文件'
    hexo_run clean
    hexo_run generate

    echo '[deploy] 只暂存博客相关改动'
    add_blog_files

    # 没有变更就不提交也不推送
    if git diff --cached --quiet; then
      echo '[deploy] 没有可提交的改动，跳过 commit/push'
      exit 0
    fi

    COMMIT_MSG="chore: deploy blog $(date '+%F %T')"
    echo "[deploy] 提交改动：${COMMIT_MSG}"
    git commit -m "$COMMIT_MSG"

    echo "[deploy] 推送到 origin/${BRANCH}"
    git push origin "$BRANCH"
    ;;
  help|-h|--help)
    usage
    ;;
  *)
    echo "未知命令: $1" >&2
    usage
    exit 1
    ;;
esac
