#!/bin/bash
# Test script for Debian Atomic Terminal Installer
# This script tests the installation process in a controlled environment

set -e

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

# Test configuration
TEST_DEVICE="/dev/loop0"
TEST_SIZE="2G"
TEST_MOUNT="/mnt/test-install"

log() {
    echo -e "${GREEN}[TEST]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
    exit 1
}

# Check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        error "This test script must be run as root"
    fi
}

# Create test device
create_test_device() {
    log "Creating test device..."
    
    # Create a loopback device for testing
    dd if=/dev/zero of=test-disk.img bs=1M count=2048
    losetup "$TEST_DEVICE" test-disk.img
    
    log "Test device created: $TEST_DEVICE"
}

# Test partitioning
test_partitioning() {
    log "Testing partitioning..."
    
    # Create partition table
    parted "$TEST_DEVICE" mklabel gpt
    
    # Get device size in MiB
    local device_size=$(parted "$TEST_DEVICE" unit MiB print | grep "Disk $TEST_DEVICE" | awk '{print $3}' | sed 's/MiB//')
    local boot_end=512
    local root_end=$((device_size - 1024))  # Leave 1GB for swap
    
    # Create test partitions
    parted "$TEST_DEVICE" mkpart primary fat32 1MiB ${boot_end}MiB
    parted "$TEST_DEVICE" set 1 boot on
    parted "$TEST_DEVICE" mkpart primary ext4 ${boot_end}MiB ${root_end}MiB
    parted "$TEST_DEVICE" mkpart primary linux-swap ${root_end}MiB 100%
    
    log "Partitioning test completed"
}

# Test filesystem creation
test_filesystems() {
    log "Testing filesystem creation..."
    
    # Format partitions
    mkfs.fat -F32 "${TEST_DEVICE}p1"
    mkfs.ext4 "${TEST_DEVICE}p2"
    mkswap "${TEST_DEVICE}p3"
    
    log "Filesystem creation test completed"
}

# Test mounting
test_mounting() {
    log "Testing mounting..."
    
    # Create mount point
    mkdir -p "$TEST_MOUNT"
    
    # Mount root partition
    mount "${TEST_DEVICE}p2" "$TEST_MOUNT"
    
    # Create and mount boot directory
    mkdir -p "$TEST_MOUNT/boot"
    mount "${TEST_DEVICE}p1" "$TEST_MOUNT/boot"
    
    # Create necessary directories for bind mounts
    mkdir -p "$TEST_MOUNT/dev"
    mkdir -p "$TEST_MOUNT/proc"
    mkdir -p "$TEST_MOUNT/sys"
    mkdir -p "$TEST_MOUNT/run"
    
    # Mount necessary filesystems
    mount --bind /dev "$TEST_MOUNT/dev"
    mount --bind /proc "$TEST_MOUNT/proc"
    mount --bind /sys "$TEST_MOUNT/sys"
    mount --bind /run "$TEST_MOUNT/run"
    
    log "Mounting test completed"
}

# Test base system installation
test_base_installation() {
    log "Testing base system installation..."
    
    # Use debootstrap to install minimal system
    debootstrap --arch=amd64 --variant=minbase bookworm "$TEST_MOUNT" http://deb.debian.org/debian/
    
    # Configure basic system
    echo "test-host" > "$TEST_MOUNT/etc/hostname"
    echo "127.0.0.1 localhost test-host" > "$TEST_MOUNT/etc/hosts"
    
    # Configure apt sources
    cat > "$TEST_MOUNT/etc/apt/sources.list" << EOF
deb http://deb.debian.org/debian bookworm main
deb http://deb.debian.org/debian bookworm-updates main
deb http://security.debian.org/debian-security bookworm-security main
EOF
    
    log "Base system installation test completed"
}

# Test user creation
test_user_creation() {
    log "Testing user creation..."
    
    # Create test user
    chroot "$TEST_MOUNT" bash -c "
        useradd -m -s /bin/bash testuser
        echo 'testuser ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/testuser
        chmod 0440 /etc/sudoers.d/testuser
    "
    
    log "User creation test completed"
}

# Test network configuration
test_network_config() {
    log "Testing network configuration..."
    
    # Enable systemd services
    chroot "$TEST_MOUNT" bash -c "
        systemctl enable systemd-networkd
        systemctl enable systemd-resolved
    "
    
    # Create network configuration
    mkdir -p "$TEST_MOUNT/etc/systemd/network"
    cat > "$TEST_MOUNT/etc/systemd/network/20-wired.network" << EOF
[Match]
Name=en*

[Network]
DHCP=yes
EOF
    
    log "Network configuration test completed"
}

# Test boot configuration
test_boot_config() {
    log "Testing boot configuration..."
    
    # Install bootc
    chroot "$TEST_MOUNT" bash -c "
        apt-get update
        apt-get install -y bootc
    "
    
    log "Boot configuration test completed"
}

# Test cleanup
test_cleanup() {
    log "Testing cleanup..."
    
    # Unmount filesystems
    umount "$TEST_MOUNT/run"
    umount "$TEST_MOUNT/sys"
    umount "$TEST_MOUNT/proc"
    umount "$TEST_MOUNT/dev"
    umount "$TEST_MOUNT/boot"
    umount "$TEST_MOUNT"
    
    # Clean up loopback device
    losetup -d "$TEST_DEVICE"
    rm -f test-disk.img
    
    log "Cleanup test completed"
}

# Run all tests
run_tests() {
    log "Starting installation tests..."
    
    check_root
    create_test_device
    test_partitioning
    test_filesystems
    test_mounting
    test_base_installation
    test_user_creation
    test_network_config
    test_boot_config
    test_cleanup
    
    log "All tests completed successfully!"
}

# Main function
main() {
    echo "Debian Atomic Terminal Installer - Test Suite"
    echo "============================================="
    echo ""
    
    run_tests
    
    echo ""
    echo "✅ All installation tests passed!"
    echo "The terminal installer should work correctly."
}

# Run main function
main "$@" 