#!/usr/bin/env bash
# Bootstrap git-based updates on production.
# Env:
#   GITEA_USER / GITEA_PASS  (required for first clone / credential store)
#   REPO_URL default https://gitea.zhengcloud.ltd/cxbsoft/WeChatRouter.git
set -euo pipefail

GITEA_USER="${GITEA_USER:-cxbsoft}"
GITEA_PASS="${GITEA_PASS:-}"
REPO_URL="${REPO_URL:-https://gitea.zhengcloud.ltd/cxbsoft/WeChatRouter.git}"
REPO_DIR="${REPO_DIR:-/opt/WeChatRouter}"
RUNTIME_DIR="${RUNTIME_DIR:-/opt/wx_router}"

if [[ -z "$GITEA_PASS" ]]; then
  echo "set GITEA_PASS"
  exit 1
fi

# credential helper for future git pull without embedding pass in remote URL
git config --global credential.helper store
cat > /root/.git-credentials <<EOF
https://${GITEA_USER}:${GITEA_PASS}@gitea.zhengcloud.ltd
EOF
chmod 600 /root/.git-credentials

if [[ ! -d "$REPO_DIR/.git" ]]; then
  rm -rf "$REPO_DIR"
  git clone "$REPO_URL" "$REPO_DIR"
else
  cd "$REPO_DIR"
  git remote set-url origin "$REPO_URL"
  git fetch origin
  git checkout main
  git pull --ff-only origin main
fi

cd "$REPO_DIR"
git remote set-url origin "$REPO_URL"
git log -1 --oneline

mkdir -p "$RUNTIME_DIR/scripts"
install -m 0755 "$REPO_DIR/deploy/update_from_git.sh" "$RUNTIME_DIR/scripts/update_from_git.sh"
# also keep a copy in repo path for discoverability
install -m 0755 "$REPO_DIR/deploy/update_from_git.sh" "$REPO_DIR/deploy/update_from_git.sh"

echo "bootstrap ok"
echo "repo: $REPO_DIR @ $(git -C "$REPO_DIR" rev-parse --short HEAD)"
echo "update: $RUNTIME_DIR/scripts/update_from_git.sh"
