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

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJECT_DIR"

# Cron 默认 PATH 往往很短，先补一份基础路径。
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"

resolve_bun() {
  # 1) PATH 可直接找到 bun
  if command -v bun >/dev/null 2>&1; then
    command -v bun
    return 0
  fi

  # 2) 允许外部显式指定 BUN_BIN
  if [[ -n "${BUN_BIN:-}" && -x "${BUN_BIN}" ]]; then
    echo "${BUN_BIN}"
    return 0
  fi

  # 3) 尝试加载 nvm 环境（root 与普通用户路径）
  local nvm_candidates=("/root/.nvm/nvm.sh" "${HOME:-}/.nvm/nvm.sh")
  local nvm_sh
  for nvm_sh in "${nvm_candidates[@]}"; do
    if [[ -s "${nvm_sh}" ]]; then
      # shellcheck source=/dev/null
      source "${nvm_sh}" >/dev/null 2>&1 || true
      if command -v bun >/dev/null 2>&1; then
        command -v bun
        return 0
      fi
    fi
  done

  # 4) 直接扫描 nvm 目录中的 bun，优先版本号最高的 Node 目录
  local bun_candidates
  bun_candidates=$(find /root/.nvm/versions/node "${HOME:-}/.nvm/versions/node" -type f -path "*/bin/bun" 2>/dev/null | sort -V || true)
  if [[ -n "${bun_candidates}" ]]; then
    echo "${bun_candidates}" | tail -n 1
    return 0
  fi

  return 1
}

if ! BUN_CMD="$(resolve_bun)"; then
  echo "[ERROR] bun 未安装或不在 PATH 中"
  exit 1
fi

if ! command -v git >/dev/null 2>&1; then
  echo "[ERROR] git 未安装或不在 PATH 中"
  exit 1
fi

if [[ ! -d .git ]]; then
  echo "[ERROR] 当前目录不是 Git 仓库: $PROJECT_DIR"
  exit 1
fi

echo "[INFO] 项目目录: $PROJECT_DIR"
echo "[INFO] bun 路径: $BUN_CMD"
echo "[INFO] 开始执行 daily 采集..."
"$BUN_CMD" run daily

echo "[INFO] 添加产物到暂存区..."
git add data pic

if git diff --cached --quiet; then
  echo "[INFO] 没有新增变更，跳过提交和推送"
  exit 0
fi

COMMIT_MSG="chore: daily data update $(date +%F)"
echo "[INFO] 提交变更: $COMMIT_MSG"
git commit -m "$COMMIT_MSG"

echo "[INFO] 推送到远端..."
git push

echo "[INFO] 执行完成"
