#!/bin/sh

set -eu

MAIN_PROJECT_ROOT="${MAIN_PROJECT_ROOT:-/workspace/main-project}"
SERVER_COMMAND_COMPOSE_FILE="${SERVER_COMMAND_COMPOSE_FILE:-$MAIN_PROJECT_ROOT/docker-compose.yml}"
SERVER_COMMAND_SERVICE="${SERVER_COMMAND_SERVICE:-prod-app}"
SERVER_COMMAND_CONTAINER_NAME="${SERVER_COMMAND_CONTAINER_NAME:-ai-code-app-prod}"
SERVER_COMMAND_DOCKER_SOCKET="${SERVER_COMMAND_DOCKER_SOCKET:-/var/run/docker.sock}"
SERVER_COMMAND_PROD_GIT_REMOTE="${SERVER_COMMAND_PROD_GIT_REMOTE:-origin}"
SERVER_COMMAND_PROD_GIT_BRANCH="${SERVER_COMMAND_PROD_GIT_BRANCH:-main}"
SERVER_COMMAND_PROD_GIT_USERNAME="${SERVER_COMMAND_PROD_GIT_USERNAME:-}"
SERVER_COMMAND_PROD_GIT_PASSWORD="${SERVER_COMMAND_PROD_GIT_PASSWORD:-}"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

cd "$MAIN_PROJECT_ROOT"

if ! command -v git >/dev/null 2>&1; then
  echo "git CLI not found: cannot pull ${SERVER_COMMAND_PROD_GIT_REMOTE}/${SERVER_COMMAND_PROD_GIT_BRANCH}" >&2
  exit 127
fi

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

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

if [ -n "$SERVER_COMMAND_PROD_GIT_USERNAME" ] && [ -n "$SERVER_COMMAND_PROD_GIT_PASSWORD" ]; then
  REMOTE_URL=$(git remote get-url "$SERVER_COMMAND_PROD_GIT_REMOTE")
  CREDENTIAL_STORE=$(mktemp)
  trap 'rm -f "$CREDENTIAL_STORE"' EXIT INT TERM
  printf '%s\n' "$REMOTE_URL" \
    | sed "s#^https://#https://${SERVER_COMMAND_PROD_GIT_USERNAME}:${SERVER_COMMAND_PROD_GIT_PASSWORD}@#" \
    >"$CREDENTIAL_STORE"
  git -c "credential.helper=store --file=$CREDENTIAL_STORE" pull --ff-only "$SERVER_COMMAND_PROD_GIT_REMOTE" "$SERVER_COMMAND_PROD_GIT_BRANCH"
else
  git pull --ff-only "$SERVER_COMMAND_PROD_GIT_REMOTE" "$SERVER_COMMAND_PROD_GIT_BRANCH"
fi

if command -v docker >/dev/null 2>&1; then
  exec docker compose -f "$SERVER_COMMAND_COMPOSE_FILE" up -d --build --force-recreate --no-deps "$SERVER_COMMAND_SERVICE"
fi

if [ -S "$SERVER_COMMAND_DOCKER_SOCKET" ]; then
  exec node "$SCRIPT_DIR/restart-via-docker-socket.mjs" "$SERVER_COMMAND_CONTAINER_NAME"
fi

echo "docker CLI not found and Docker socket is unavailable: $SERVER_COMMAND_DOCKER_SOCKET" >&2
exit 127
