#!/bin/bash
set -euo pipefail

REPO_DIR="/opt/clawd"
REMOTE="origin"
BRANCH="main"
SERVICE="clawd.service"
NO_RESTART=false
NO_PULL=false

for arg in "$@"; do
  case "$arg" in
    --no-restart) NO_RESTART=true ;;
    --no-pull)    NO_PULL=true ;;
  esac
done

echo "==> clawd update start"
date

if [ ! -d "$REPO_DIR/.git" ]; then
  echo "ERROR: $REPO_DIR is not a git repository"
  exit 1
fi

cd "$REPO_DIR"

if [ "$NO_PULL" = false ]; then
  # 如果 remote 仍指向 GitHub，迁移到 git.cutos.ai
  CURRENT_REMOTE=$(git remote get-url "$REMOTE" 2>/dev/null || echo "")
  if echo "$CURRENT_REMOTE" | grep -q "github.com"; then
    echo "==> Migrating remote from GitHub to git.cutos.ai ..."
    git remote set-url "$REMOTE" https://git.cutos.ai/claw-daemon/clawd.git
  fi

  echo "==> Fetching latest from $REMOTE/$BRANCH ..."
  git fetch "$REMOTE"

  LOCAL_COMMIT="$(git rev-parse HEAD)"
  REMOTE_COMMIT="$(git rev-parse "$REMOTE/$BRANCH")"

  echo "==> Local : $LOCAL_COMMIT"
  echo "==> Remote: $REMOTE_COMMIT"

  if [ "$LOCAL_COMMIT" = "$REMOTE_COMMIT" ]; then
    echo "==> Already up to date. Skip upgrade."
    exit 0
  fi

  echo "==> Updating working tree to $REMOTE/$BRANCH ..."
  git reset --hard "$REMOTE/$BRANCH"
  git clean -fd

  # Re-exec the freshly pulled version of this script so all new logic runs
  echo "==> Re-executing updated script ..."
  exec bash "$REPO_DIR/tools/update-clawd.sh" --no-pull "$@"
fi

# ── 以下由新版脚本执行（--no-pull 阶段）────────────────────────────────────────

LOCAL_COMMIT="$(git rev-parse HEAD)"
REMOTE_COMMIT="$(git rev-parse "$REMOTE/$BRANCH" 2>/dev/null || echo "$LOCAL_COMMIT")"

if git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -Eq '(^|/)(package.json|package-lock.json)$'; then
  echo "==> Dependency files changed, running npm install ..."
  npm install --prefix "$REPO_DIR"
else
  echo "==> No dependency changes, skip npm install"
fi

echo "==> Current commit:"
git log --oneline -1

if [ "$NO_RESTART" = true ]; then
  echo "==> --no-restart: skip systemctl restart (caller handles restart)"
  exit 0
fi

echo "==> Restarting service: $SERVICE"
systemctl restart "$SERVICE"

echo "==> Service status:"
systemctl status "$SERVICE" --no-pager -l || true

echo "==> clawd update done"