#!/usr/bin/env bash
# P83 — verhindert "alter Code im Container"-Bug.
#
# Vergleicht den im Container deployten git-SHA mit dem aktuellen
# Source-SHA. Wenn abweichend → exit 1 mit Hinweis Build/Recreate.
#
# Aufruf-Beispiele:
#   ./scripts/check-rebuild-needed.sh backend-compliance
#   ./scripts/check-rebuild-needed.sh admin-compliance
#   ./scripts/check-rebuild-needed.sh consent-tester
#
# CI-Verwendung: nach git push, vor dem ersten Health-Check.
# Lokal: claude / dev kann es via pre-merge-hook nutzen.
#
# Voraussetzung: Container hat BUILD_SHA env (gesetzt im Dockerfile via
# ARG BUILD_SHA + ENV BUILD_SHA=$BUILD_SHA). Falls leer → Warnung.

set -e

SERVICE="${1:-backend-compliance}"
CONTAINER="bp-compliance-${SERVICE#*-}"   # backend-compliance → bp-compliance-backend
if [[ "$SERVICE" == "consent-tester" ]]; then
    CONTAINER="bp-compliance-consent-tester"
fi

DOCKER="${DOCKER:-/usr/local/bin/docker}"

deployed_sha=$($DOCKER exec "$CONTAINER" sh -c 'echo "${BUILD_SHA:-unknown}"' 2>/dev/null || echo "container-down")
local_sha=$(git rev-parse --short HEAD)

if [[ "$deployed_sha" == "container-down" ]]; then
    echo "❌ Container $CONTAINER is not running"
    exit 2
fi

if [[ "$deployed_sha" == "unknown" ]]; then
    echo "⚠️  $CONTAINER has no BUILD_SHA env — cannot verify."
    echo "    Add to Dockerfile: ARG BUILD_SHA / ENV BUILD_SHA=\$BUILD_SHA"
    exit 0
fi

if [[ "$deployed_sha" != "$local_sha"* && "$local_sha" != "$deployed_sha"* ]]; then
    echo "❌ $CONTAINER is on commit $deployed_sha, local is $local_sha"
    echo "    REBUILD REQUIRED:"
    echo "    docker compose build $SERVICE && docker compose up -d --no-deps --force-recreate $SERVICE"
    exit 1
fi

echo "✓ $CONTAINER ($deployed_sha) matches local ($local_sha)"
