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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="$TEST_ROOT/.env"

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

docker container rm -f argus-agent-e2e >/dev/null 2>&1 || true

pushd "$TEST_ROOT" >/dev/null
compose down --remove-orphans
popd >/dev/null

if [[ -d "$TEST_ROOT/private" ]]; then
  docker run --rm \
    -v "$TEST_ROOT/private:/target" \
    ubuntu:24.04 \
    chown -R "$(id -u):$(id -g)" /target >/dev/null 2>&1 || true
  rm -rf "$TEST_ROOT/private"
fi

rm -rf "$TEST_ROOT/tmp"

if [[ -f "$ENV_FILE" ]]; then
  rm -f "$ENV_FILE"
fi

echo "[INFO] Agent E2E environment cleaned up"
