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

# CI step: modify config for deployment
# Called from .gitea/workflows/deploy.yml

# Enable sentry
sed -i 's#\(sentryEnvironment.*\)".*"#\1"'"${GITHUB_REF_NAME}"'"#g' frontend/src/config.ts
sed -i 's#//\( sentry\\.init.*\)#\1#g' frontend/src/config.ts
sed -i 's#metrictCall = false#metrictCall = true#g' frontend/src/config.ts

# Build release string from git info
set -o allexport
. ./.env
echo "PROJECT_RELEASE=${SENTRY_PROJECT}.r$(git rev-list HEAD --count)-$(git describe --all --long | sed 's+/+-+')" >> .env
. ./.env
set +o allexport

echo "______ .env ______"
cat .env
echo

# Inject release and origin URL into hooks
sed -i 's#\(const release = \).*#\1"'"${PROJECT_RELEASE}"'"#g' api/hooks/config-client.js
sed -i 's#\(const originURL = \).*#\1"'"${LIVE_URL}"'"#g' api/hooks/config-client.js

# Inject cache-busting timestamp
stamp=$(date +%s)
sed -i "s/__TIMESTAMP__/${stamp}/g" frontend/spa.html

# Copy spa.html to api/templates (remove symlink or file first)
if [ -d api/templates ]; then
    [ -L api/templates/spa.html ] && rm api/templates/spa.html
    [ -f api/templates/spa.html ] && rm api/templates/spa.html
    cp frontend/spa.html api/templates/spa.html
fi

echo "______ frontend/spa.html ______"
cat frontend/spa.html

# Set preview URL
sed -i 's#\(PREVIEW_URL=\).*#\1'"${LIVE_URL}"'/preview#g' api/config.yml.env

echo "______ api/config.yml.env ______"
cat api/config.yml.env
