#!/bin/sh
set -eu

VERSION="${1:-${RELEASE_VERSION:-}}"
if [ -z "$VERSION" ]; then
  echo "Usage: $0 <version> <runtime-images.tar>"
  exit 1
fi

IMAGE_TAR="${2:-${RUNTIME_IMAGE_TAR:-}}"
if [ -z "$IMAGE_TAR" ]; then
  echo "Usage: $0 <version> <runtime-images.tar>"
  exit 1
fi

HOST_PREFIX="${HOST_PREFIX-/host}"
PRODUCTION_ROOT="$HOST_PREFIX/var/lib/xiaoxia-saas-production"
REPO_DIR="$PRODUCTION_ROOT/repo"
ENV_FILE="$PRODUCTION_ROOT/.env"
TARGET_TAR="$PRODUCTION_ROOT/runtime-images-$VERSION.tar"

if [ ! -f "$IMAGE_TAR" ]; then
  echo "Missing runtime image tar: $IMAGE_TAR"
  exit 1
fi

if [ ! -d "$REPO_DIR" ]; then
  echo "Missing production repo artifact: $REPO_DIR"
  exit 1
fi

if [ ! -f "$ENV_FILE" ]; then
  echo "Missing production env file: $ENV_FILE"
  exit 1
fi

mkdir -p "$PRODUCTION_ROOT"
cp "$IMAGE_TAR" "$TARGET_TAR"
docker load -i "$TARGET_TAR"

cd "$REPO_DIR/infra/docker"
export COMPOSE_PROJECT_NAME=xiaoxia-production-app
export WEB_DOCKERFILE=infra/docker/web-artifact.Dockerfile
export WEB_NGINX_CONF=infra/docker/nginx-production.conf
export API_IMAGE="xiaoxia-saas-api:$VERSION"
export WORKER_IMAGE="xiaoxia-saas-worker:$VERSION"
export ALLOW_PRODUCTION_BUILDS=false

if [ ! -f "$REPO_DIR/apps/web/dist/index.html" ]; then
  echo "Missing prebuilt web artifact: $REPO_DIR/apps/web/dist/index.html"
  exit 1
fi

cp "$ENV_FILE" "$REPO_DIR/.env"
docker compose --env-file "$ENV_FILE" build --pull=false web
docker compose --env-file "$ENV_FILE" run --rm --no-deps api sh -c '
  cd /app &&
  python /app/scripts/validate_release_env.py --from-environ --strict-external &&
  alembic upgrade head
'
docker compose --env-file "$ENV_FILE" up -d api worker web
docker compose --env-file "$ENV_FILE" ps
