#!/bin/sh

set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
MAIN_PROJECT_ROOT="${MAIN_PROJECT_ROOT:-/workspace/main-project}"
REPO_ROOT="${REPO_ROOT:-$MAIN_PROJECT_ROOT}"
TEST_DEPLOY_GIT_REMOTE="${TEST_DEPLOY_GIT_REMOTE:-origin}"
TEST_DEPLOY_GIT_BRANCH="${TEST_DEPLOY_GIT_BRANCH:-main}"
TEST_BUILD_COMMAND="${TEST_BUILD_COMMAND:-npm run build:test-app}"
TEST_SERVER_RESTART_SCRIPT="${TEST_SERVER_RESTART_SCRIPT:-$SCRIPT_DIR/restart-test.sh}"
TEST_DEPLOY_COMMIT_MESSAGE="${TEST_DEPLOY_COMMIT_MESSAGE:-chore: test deploy snapshot}"

cd "$MAIN_PROJECT_ROOT"

if ! command -v git >/dev/null 2>&1; then
  echo "git CLI not found" >&2
  exit 127
fi

if ! command -v npm >/dev/null 2>&1; then
  echo "npm CLI not found" >&2
  exit 127
fi

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)

if [ "$CURRENT_BRANCH" != "$TEST_DEPLOY_GIT_BRANCH" ]; then
  echo "expected branch ${TEST_DEPLOY_GIT_BRANCH} in $MAIN_PROJECT_ROOT, got ${CURRENT_BRANCH:-unknown}" >&2
  exit 1
fi

echo "::step::commit-main-worktree"
git add -A -- .   ':(exclude).server-command-test-app-built-at'   ':(exclude,glob)tmp-*'   ':(exclude,glob)tmp-verification/**'

if git diff --cached --quiet; then
  echo "no commit needed; main worktree already committed"
else
  echo "staged files for TEST deploy commit:"
  git diff --cached --name-status
  git commit -m "$TEST_DEPLOY_COMMIT_MESSAGE"
fi

echo "::step::push-origin-main"
git push "$TEST_DEPLOY_GIT_REMOTE" "$TEST_DEPLOY_GIT_BRANCH"

echo "::step::build-test-app"
sh -lc "$TEST_BUILD_COMMAND"

echo "::step::deploy-test-server"
REPO_ROOT="$REPO_ROOT" sh "$TEST_SERVER_RESTART_SCRIPT"
