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

: "${IMAGE_TAG:?IMAGE_TAG is required}"
: "${REGISTRY:?REGISTRY is required}"
: "${APP_BASE_URL:?APP_BASE_URL is required}"

exec 9>/var/lock/travel-planner-deploy.lock
flock -n 9 || { echo "Another deployment is already running" >&2; exit 1; }

if [[ -f .deployed-image-tag ]]; then
  cp .deployed-image-tag .previous-image-tag
fi

export IMAGE_TAG REGISTRY

docker compose pull edge api worker postgres redis
docker compose up -d postgres redis --wait --wait-timeout 120
docker compose run --rm --no-deps api node backend/dist/apps/api/src/migration.js
docker compose up -d --remove-orphans --wait --wait-timeout 120
scripts/teamcity/smoke.sh
printf '%s\n' "$IMAGE_TAG" > .deployed-image-tag
