#!/usr/bin/env bash
# Build and start a compose profile for apps/<slug>/ on boka.
# Called from .gitea/workflows/deploy-app.yml (workflow_dispatch only).
set -euo pipefail

APP="${1:?usage: deploy-app.sh <app-slug>}"
DEPLOY_ROOT="${DEPLOY_ROOT:-/home/frank/playground.schwenk.online}"
BRANCH="${DEPLOY_BRANCH:-main}"
APP_DIR="${DEPLOY_ROOT}/apps/${APP}"

if ! echo "${APP}" | grep -qE '^[a-z0-9]+(-[a-z0-9]+)*$'; then
  echo "Error: invalid app slug: ${APP}"
  exit 1
fi

if [ ! -d "${APP_DIR}" ]; then
  echo "Error: ${APP_DIR} does not exist"
  exit 1
fi

git_cmd() {
  git -c "safe.directory=${DEPLOY_ROOT}" -C "${DEPLOY_ROOT}" "$@"
}

if [ -n "${DEPLOY_GIT_TOKEN:-}" ]; then
  pull_url="https://oauth2:${DEPLOY_GIT_TOKEN}@gitea.schwenk.online/froxxxy/playground.git"
  git_cmd pull "${pull_url}" "${BRANCH}"
else
  git_cmd pull "https://gitea.schwenk.online/froxxxy/playground.git" "${BRANCH}"
fi

if [ -f "${APP_DIR}/package.json" ] && [ -f "${APP_DIR}/package-lock.json" ]; then
  echo "Running npm ci && npm run build in apps/${APP}..."
  docker run --rm \
    -v "${APP_DIR}:/app" \
    -w /app \
    node:current-alpine \
    sh -c "npm ci && npm run build"
fi

cd "${DEPLOY_ROOT}"
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-playground}"
docker compose --profile "${APP}" up -d --build

echo "Deploy completed for apps/${APP}"
