#!/bin/bash

# Clean up test environment and containers
# Usage: ./05_cleanup.sh [--full]

set -e

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

# Parse command line arguments
FULL_CLEANUP=true
while [[ $# -gt 0 ]]; do
    case $1 in
        --full)
            FULL_CLEANUP=true
            shift
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--full]"
            echo "  --full: Also remove persistent data "
            exit 1
            ;;
    esac
done

cd "$TEST_DIR"

echo "=== Cleaning up BIND9 test environment ==="

echo ""
echo "Step 1: Stopping and removing containers..."

# Stop and remove containers
docker compose down -v

echo "✓ Containers stopped and removed"

echo ""
echo "Step 2: Removing Docker networks..."

# Clean up networks
docker network prune -f > /dev/null 2>&1 || true

echo "✓ Docker networks cleaned"

if [ "$FULL_CLEANUP" = true ]; then
    echo ""
    echo "Step 3: Removing persistent data..."

    # Remove persistent data directory
    if [ -d "private" ]; then
        rm -rf private
        echo "✓ Persistent data directory removed"
    else
        echo "✓ No persistent data directory found"
    fi

else
    echo ""
    echo "Step 3: Preserving persistent data and Docker image..."
    echo "✓ Persistent data preserved in: private/"
    echo "✓ Docker image 'argus-bind9:latest' preserved"
    echo ""
    echo "To perform full cleanup including persistent data and image, run:"
    echo "  $0 --full"
fi

echo ""
echo "=== Cleanup Summary ==="
echo "✓ Containers stopped and removed"
echo "✓ Docker networks cleaned"

if [ "$FULL_CLEANUP" = true ]; then
    echo "✓ Persistent data removed"
    echo ""
    echo "Full cleanup completed! Test environment completely removed."
else
    echo "✓ Persistent data preserved"
    echo "✓ Docker image preserved"
    echo ""
    echo "Basic cleanup completed! Run './01_start_container.sh' to restart testing."
fi

echo ""
echo "Test environment cleanup finished."
