#!/usr/bin/env bash
# 用法:
#   prd-tool.sh commit <项目名> "<说明>"     自动 init(如需) 并提交 commit
#   prd-tool.sh push <项目名> existing        仅设 remote 并 push(用户确认已有仓库)
#   prd-tool.sh push <项目名> new             创建私有仓库后 push
# 仓库名 = 项目名(须为英文/数字/-,中文项目名请显式传 REPO=xxx)
set -euo pipefail
OWNER=hi-mcwolf; BASE=/home/html
cmd=${1:?}; proj=${2:?}; dir="$BASE/$proj"
[ -d "$dir" ] || { echo "目录不存在: $dir"; exit 1; }
cd "$dir"
repo=${REPO:-$proj}
case "$cmd" in
 commit)
  [ -d .git ] || git init -q
  git add -A
  if git diff --cached --quiet; then echo "无变更,不提交"; else git commit -q -m "${3:-update $(date '+%F %T')}" && git log --oneline -1; fi ;;
 push)
  mode=${3:?existing|new}
  TOKEN=${GITHUB_TOKEN:-$(cat /root/.github_token 2>/dev/null || true)}
  [ -n "$TOKEN" ] || { echo "缺少 GitHub Token(环境变量 GITHUB_TOKEN 或 /root/.github_token)"; exit 2; }
  if [ "$mode" = new ]; then
    code=$(curl -s -o /tmp/gh_resp.json -w '%{http_code}' -X POST https://api.github.com/user/repos \
      -H "Authorization: Bearer $TOKEN" -d "{\"name\":\"$repo\",\"private\":true}")
    [ "$code" = 201 ] || { echo "创建仓库失败 HTTP $code"; cat /tmp/gh_resp.json; exit 3; }
  fi
  url="https://github.com/$OWNER/$repo.git"
  git remote get-url origin >/dev/null 2>&1 || git remote add origin "$url"
  git -c http.extraheader="Authorization: Basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" push -u origin main
  echo "已推送 $url" ;;
 *) echo "未知命令"; exit 1;;
esac
