#!/usr/bin/env bash
set -euo pipefail

# CI step: deploy to staging environment
# Called from .gitea/workflows/deploy.yml
# Required env: API_BASEDIR, COMPOSE_PROJECT_NAME

# Read .env
set -o allexport
. ./.env
. ./api/config.yml.env
set +o allexport

# Sanitize compose project name (replace / with -)
COMPOSE_PROJECT_NAME=$(echo "${COMPOSE_PROJECT_NAME}" | sed 's+/+-+g')
export COMPOSE_PROJECT_NAME

# Sync files to staging directory
mkdir -p "${API_BASEDIR}/frontend"
rsync -av api "${API_BASEDIR}/"
rsync -av frontend/dist "${API_BASEDIR}/frontend/"
rsync -av frontend/assets "${API_BASEDIR}/frontend/"
sed -i 's#\(PREVIEW_URL=\).*#\1'"${STAGING_URL}"'/preview#g' "${API_BASEDIR}/api/config.yml.env"

# Start staging stack
docker compose -f docker-compose-staging.yml -p "${COMPOSE_PROJECT_NAME}" up -d --build --remove-orphans

# Wait for API to be ready
sleep 5

# Reload tibi-server config
reloadUrl="${STAGING_URL}/api/_/admin/reload"
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${ADMIN_TOKEN}" -d '{}' "${reloadUrl}"

# Clear SSR cache
ssrUrl="${STAGING_URL}/api/ssr"
curl -X POST -H "Content-Type: application/json" -d '{}' "${ssrUrl}?clear=1"
