#!/bin/bash

# Script to run setup tests in Docker containers
# This allows testing the setup process in isolated environments

set -e  # Exit on error

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Check if Docker is installed and working
if ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: Docker is not installed. Please install Docker to run tests.${NC}"
    exit 1
fi

# Create logs directory at the top level to ensure it exists
LOGS_DIR="$(pwd)/logs"
if [ ! -d "$LOGS_DIR" ]; then
    echo -e "${YELLOW}Creating logs directory at: $LOGS_DIR${NC}"
    mkdir -p "$LOGS_DIR" || {
        echo -e "${RED}Failed to create logs directory! Check permissions.${NC}"
        exit 1
    }
else
    echo -e "${GREEN}Logs directory already exists at: $LOGS_DIR${NC}"
fi

# Ensure the logs directory is writable
if [ ! -w "$LOGS_DIR" ]; then
    echo -e "${YELLOW}Setting permissions on logs directory...${NC}"
    chmod -R 755 "$LOGS_DIR" && \
    find "$LOGS_DIR" -type f -exec chmod 644 {} \; || {
        echo -e "${RED}Failed to set write permissions on logs directory!${NC}"
        exit 1
    }
fi

# Create a test file to verify we can write to it
if touch "$LOGS_DIR/test_file" && rm "$LOGS_DIR/test_file"; then
    echo -e "${GREEN}Log directory is writable and ready for use${NC}"
else
    echo -e "${RED}Cannot write to logs directory even after setting permissions!${NC}"
    exit 1
fi

# Check if Docker is running
if ! docker info &>/dev/null; then
    echo -e "${YELLOW}Warning: Docker appears to be installed but not running or not properly configured.${NC}"
    echo -e "${YELLOW}If using WSL2, ensure Docker Desktop is running with WSL integration enabled.${NC}"
    echo -e "${YELLOW}Would you like to run the local test instead? [Y/n]${NC}"
    read -r response
    if [[ "$response" =~ ^([nN][oO]|[nN])$ ]]; then
        echo -e "${RED}Exiting...${NC}"
        exit 1
    else
        echo -e "${BLUE}Running local test instead...${NC}"
        ./test-setup.sh
        exit $?
    fi
fi

# Build and run Ubuntu test container
run_ubuntu_test() {
    echo -e "\n${BLUE}=== Running test in Ubuntu container ===${NC}"
    # Create the logs directory if it doesn't exist
    local log_dir="$(pwd)/logs"
    mkdir -p "$log_dir" || true

    # Use sudo for chmod only if necessary
    if [ ! -w "$log_dir" ]; then
        echo -e "${YELLOW}Attempting to fix permissions with sudo...${NC}"
        sudo chmod -R 755 "$log_dir" 2>/dev/null && \
        sudo find "$log_dir" -type f -exec chmod 644 {} \; 2>/dev/null || {
            echo -e "${YELLOW}Could not change permissions with sudo, continuing anyway...${NC}"
        }
    fi

    echo -e "${YELLOW}Logs will be saved to: $log_dir${NC}"
    echo -e "${YELLOW}Building Ubuntu test container...${NC}"
    docker build --target ubuntu-test -t shell-test:ubuntu .

    echo -e "${GREEN}Running tests with package installation...${NC}"

    # Create a timestamp for this test run
    TEST_TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
    echo -e "${YELLOW}Test run timestamp: $TEST_TIMESTAMP${NC}"

    # Run container with proper volume mount and add environment variable for timestamp
    docker run --rm -it \
        -e TEST_TIMESTAMP="$TEST_TIMESTAMP" \
        -e CONTAINER_TYPE="ubuntu" \
        -v "$log_dir:/logs:z" \
        shell-test:ubuntu

    # Check if logs were created
    if ls "$log_dir"/setup-test-*"$TEST_TIMESTAMP"* &>/dev/null 2>&1; then
        echo -e "${GREEN}Test logs successfully created in host directory${NC}"
    else
        echo -e "${YELLOW}Warning: No log files found matching timestamp $TEST_TIMESTAMP${NC}"
        echo -e "${YELLOW}This may indicate issues with volume mounting or permissions${NC}"
        echo -e "${YELLOW}Contents of log directory:${NC}"
        ls -la "$log_dir" || echo "Cannot list directory contents"
    fi

    echo -e "${BLUE}Test completed. Check logs in $log_dir directory${NC}"
}

# Build and run Debian test container
run_debian_test() {
    echo -e "\n${BLUE}=== Running test in Debian container ===${NC}"
    # Create the logs directory if it doesn't exist
    local log_dir="$(pwd)/logs"
    mkdir -p "$log_dir" || true

    # Use sudo for chmod only if necessary
    if [ ! -w "$log_dir" ]; then
        echo -e "${YELLOW}Attempting to fix permissions with sudo...${NC}"
        sudo chmod -R 755 "$log_dir" 2>/dev/null && \
        sudo find "$log_dir" -type f -exec chmod 644 {} \; 2>/dev/null || {
            echo -e "${YELLOW}Could not change permissions with sudo, continuing anyway...${NC}"
        }
    fi

    echo -e "${YELLOW}Logs will be saved to: $log_dir${NC}"
    echo -e "${YELLOW}Building Debian test container...${NC}"
    docker build --target debian-test -t shell-test:debian .

    echo -e "${GREEN}Running tests with package installation...${NC}"

    # Create a timestamp for this test run
    TEST_TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
    echo -e "${YELLOW}Test run timestamp: $TEST_TIMESTAMP${NC}"

    # Run container with proper volume mount and add environment variable for timestamp
    docker run --rm -it \
        -e TEST_TIMESTAMP="$TEST_TIMESTAMP" \
        -e CONTAINER_TYPE="debian" \
        -v "$log_dir:/logs:z" \
        shell-test:debian

    # Check if logs were created
    if ls "$log_dir"/setup-test-*"$TEST_TIMESTAMP"* &>/dev/null 2>&1; then
        echo -e "${GREEN}Test logs successfully created in host directory${NC}"
    else
        echo -e "${YELLOW}Warning: No log files found matching timestamp $TEST_TIMESTAMP${NC}"
        echo -e "${YELLOW}This may indicate issues with volume mounting or permissions${NC}"
        echo -e "${YELLOW}Contents of log directory:${NC}"
        ls -la "$log_dir" || echo "Cannot list directory contents"
    fi

    echo -e "${BLUE}Test completed. Check logs in $log_dir directory${NC}"
}

# Full test with bootstrap script
run_full_test() {
    local distro=$1
    local tag_name=$(echo $distro | sed 's/:/-/g')  # Replace colon with hyphen for tag
    echo -e "\n${BLUE}=== Running full bootstrap test in $distro container ===${NC}"

    # Create a Dockerfile for full test
    cat > Dockerfile.fulltest <<EOF
FROM $distro
LABEL description="$distro full test environment for bootstrap.sh script"

# Install minimal dependencies needed to run the bootstrap
ENV TZ=America/New_York
ENV DEBIAN_FRONTEND=noninteractive
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \
    && apt-get update && apt-get install -y curl git sudo wget

# Create a test user with sudo permissions
RUN useradd -ms /bin/bash testuser && \\
    echo "testuser ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/testuser

# Create directory structure for setup files
RUN mkdir -p /home/testuser/shell

# Copy test script for post-bootstrap validation
COPY --chown=testuser:testuser test-setup.sh /home/testuser/

# Copy entire repo structure to ensure we have all needed files
COPY --chown=testuser:testuser . /home/testuser/shell/

USER testuser
WORKDIR /home/testuser

# Make the script executable
RUN chmod +x /home/testuser/test-setup.sh

# Run tests before and after bootstrap to verify package installation
CMD ["/bin/bash", "-c", "echo -e '\\n\\nRunning pre-bootstrap tests...' && ./test-setup.sh && echo -e '\\n\\nRunning bootstrap...' && /home/testuser/shell/bootstrap.sh && echo -e '\\n\\nRunning post-bootstrap tests...' && ./test-setup.sh"]
EOF

    # Build and run the container
    # Create the logs directory if it doesn't exist
    mkdir -p "$(pwd)/logs"
    docker build -f Dockerfile.fulltest -t shell-full-test:$tag_name .
    docker run --rm -it -v "$(pwd)/logs:/logs" shell-full-test:$tag_name

    # Clean up
    rm Dockerfile.fulltest
}

# Parse command line arguments
case "$1" in
    ubuntu)
        run_ubuntu_test
        ;;
    debian)
        run_debian_test
        ;;
    full-ubuntu)
        run_full_test "ubuntu:24.04"
        ;;
    full-debian)
        run_full_test "debian:12"
        ;;
    all)
        run_ubuntu_test
        run_debian_test
        ;;
    *)
        echo -e "${BLUE}Shell Setup Test Runner${NC}"
        echo -e "Usage: $0 [option]"
        echo -e "\nOptions:"
        echo "  ubuntu      Run test on Ubuntu container (tests packages and components)"
        echo "  debian      Run test on Debian container (tests packages and components)"
        echo "  full-ubuntu Run full bootstrap test on Ubuntu container (performs complete installation)"
        echo "  full-debian Run full bootstrap test on Debian container (performs complete installation)"
        echo "  all         Run tests on both Ubuntu and Debian containers (component tests only)"
        echo -e "\nExamples:"
        echo -e "  $0 ubuntu      # Quick test for package availability"
        echo -e "  $0 full-debian # Test complete bootstrap installation"
        ;;
esac
