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

log() {
  printf '[redeploy] %s\n' "$*"
}

if [[ ! -d .git ]]; then
  printf '[redeploy] ERROR: run this script from the repository root.\n' >&2
  exit 1
fi

OLD_COMPOSE_FILE="$(mktemp)"

cleanup() {
  if [[ -f "$OLD_COMPOSE_FILE" ]]; then
    rm -f "$OLD_COMPOSE_FILE"
  fi
}
trap cleanup EXIT

log 'Capturing current compose configuration'
docker compose config > "$OLD_COMPOSE_FILE"

log 'Pulling latest git changes'
git pull

log 'Building updated images while current stack is running'
docker compose build --no-cache

log 'Stopping previous stack using captured configuration'
docker compose --project-directory "$PWD" -f "$OLD_COMPOSE_FILE" down

log 'Starting stack'
docker compose up -d

log 'Redeploy complete'
