#!/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:-release-app}"
SERVER_COMMAND_CONTAINER_NAME="${SERVER_COMMAND_CONTAINER_NAME:-ai-code-app-release}"
SERVER_COMMAND_DOCKER_SOCKET="${SERVER_COMMAND_DOCKER_SOCKET:-/var/run/docker.sock}"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

cd "$MAIN_PROJECT_ROOT"

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
