#!/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

log 'Stopping stack'
docker compose down

log 'Removing current local compose image(s)'
mapfile -t IMAGE_NAMES < <(docker compose config --images 2>/dev/null | sed '/^$/d' | sort -u)
if [[ "${#IMAGE_NAMES[@]}" -gt 0 ]]; then
  docker image rm -f "${IMAGE_NAMES[@]}" || true
else
  log 'No compose-managed local images found to remove.'
fi

log 'Pulling latest git changes'
git pull

log 'Starting stack'
docker compose up -d

log 'Redeploy complete'
