#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

CONTAINER_NAME="azaion-detections"
GRACE_PERIOD=30

usage() {
    echo "Usage: $0 [--help]"
    echo "Gracefully stop Azaion.Detections service container."
    exit 0
}

for arg in "$@"; do
    case "$arg" in
        --help) usage ;;
    esac
done

if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    CURRENT_IMAGE="$(docker inspect --format='{{.Config.Image}}' "$CONTAINER_NAME" 2>/dev/null || true)"
    if [ -n "$CURRENT_IMAGE" ]; then
        CURRENT_TAG="${CURRENT_IMAGE##*:}"
        echo "$CURRENT_TAG" > "$PROJECT_ROOT/.deploy-previous-tag"
        echo "Saved previous tag: $CURRENT_TAG"
    fi

    echo "Stopping $CONTAINER_NAME (${GRACE_PERIOD}s grace period)..."
    docker stop -t "$GRACE_PERIOD" "$CONTAINER_NAME" || true
    docker rm "$CONTAINER_NAME" 2>/dev/null || true
    echo "Stopped and removed $CONTAINER_NAME."
else
    echo "Container $CONTAINER_NAME is not running."
fi

docker container prune -f --filter "label=com.docker.compose.project=azaion-detections" 2>/dev/null || true
