#!/usr/bin/env bash
# Rollback to a previous image tag
set -euo pipefail

IMAGE_TAG="${1:?Usage: rollback.sh <previous-image-tag>}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
RELEASE_FILE="/opt/helix/releases/current"

echo "=== Rolling back to tag: ${IMAGE_TAG} ==="

# Pull the previous images (should be cached)
"$SCRIPT_DIR/pull-images.sh" "$IMAGE_TAG"

# NOTE: We do NOT run reverse migrations — migrations should be forward-compatible
echo "Skipping migration rollback (migrations must be forward-compatible)"

# Restart with previous images
cd /opt/helix/compose
docker compose -f docker-compose.prod.yml up -d --remove-orphans

# Health check
if "$SCRIPT_DIR/healthcheck.sh"; then
  echo "$IMAGE_TAG" > "$RELEASE_FILE"
  echo "=== Rollback successful (tag: ${IMAGE_TAG}) ==="
else
  echo "=== Rollback FAILED — manual intervention required ==="
  exit 1
fi
