#!/bin/bash
# Debian Atomic Terminal Installer
# Automated installation script for Debian Atomic

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

# Configuration
TARGET_DEVICE="/dev/sda"
ROOT_PARTITION="/dev/sda1"
BOOT_PARTITION="/dev/sda2"
SWAP_PARTITION="/dev/sda3"
USERNAME="debian"
HOSTNAME="debian-atomic"
TIMEZONE="UTC"

# Logging
LOG_FILE="/tmp/install.log"
exec > >(tee -a "$LOG_FILE") 2>&1

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${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 script must be run as root"
    fi
}

# Check if we're in a live environment
check_live_environment() {
    if ! mountpoint -q /run/archiso/bootmnt 2>/dev/null && ! grep -q "boot=live" /proc/cmdline; then
        warn "This doesn't appear to be a live environment. Proceed anyway? (y/N)"
        read -r response
        if [[ ! "$response" =~ ^[Yy]$ ]]; then
            error "Installation aborted"
        fi
    fi
}

# Detect target device
detect_target_device() {
    log "Detecting target device..."
    
    # List available block devices
    echo "Available block devices:"
    lsblk -d -o NAME,SIZE,TYPE
    
    # Try to auto-detect the target device
    if [[ "$TARGET_DEVICE" == "/dev/sda" ]]; then
        # Look for the largest non-removable disk
        local largest_disk=""
        local largest_size=0
        
        for disk in /dev/sd* /dev/vd* /dev/nvme*; do
            if [[ -b "$disk" ]]; then
                local size=$(lsblk -d -n -o SIZE "$disk" | sed 's/[^0-9]//g')
                if [[ "$size" -gt "$largest_size" ]]; then
                    largest_size="$size"
                    largest_disk="$disk"
                fi
            fi
        done
        
        if [[ -n "$largest_disk" ]]; then
            TARGET_DEVICE="$largest_disk"
            log "Auto-detected target device: $TARGET_DEVICE"
        fi
    fi
    
    echo "Target device: $TARGET_DEVICE"
    echo "Proceed with installation? (y/N)"
    read -r response
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        error "Installation aborted"
    fi
}

# Partition the target device
partition_device() {
    log "Partitioning target device: $TARGET_DEVICE"
    
    # Create partition table
    parted "$TARGET_DEVICE" mklabel gpt
    
    # Create partitions
    # Boot partition (512MB)
    parted "$TARGET_DEVICE" mkpart primary fat32 1MiB 513MiB
    parted "$TARGET_DEVICE" set 1 boot on
    
    # Root partition (rest of disk minus 8GB for swap)
    local total_size=$(parted "$TARGET_DEVICE" unit MiB print | grep "Disk $TARGET_DEVICE" | awk '{print $3}' | sed 's/MiB//')
    local root_end=$((total_size - 8192))
    parted "$TARGET_DEVICE" mkpart primary ext4 513MiB ${root_end}MiB
    
    # Swap partition (8GB)
    parted "$TARGET_DEVICE" mkpart primary linux-swap ${root_end}MiB 100%
    
    # Update partition variables
    ROOT_PARTITION="${TARGET_DEVICE}2"
    BOOT_PARTITION="${TARGET_DEVICE}1"
    SWAP_PARTITION="${TARGET_DEVICE}3"
    
    log "Partitioning complete"
}

# Format partitions
format_partitions() {
    log "Formatting partitions..."
    
    # Format boot partition
    mkfs.fat -F32 "$BOOT_PARTITION"
    
    # Format root partition
    mkfs.ext4 "$ROOT_PARTITION"
    
    # Format swap partition
    mkswap "$SWAP_PARTITION"
    
    log "Partition formatting complete"
}

# Mount target filesystem
mount_target() {
    log "Mounting target filesystem..."
    
    # Create mount point
    mkdir -p /mnt/target
    
    # Mount root partition
    mount "$ROOT_PARTITION" /mnt/target
    
    # Create and mount boot directory
    mkdir -p /mnt/target/boot
    mount "$BOOT_PARTITION" /mnt/target/boot
    
    # Mount necessary filesystems
    mount --bind /dev /mnt/target/dev
    mount --bind /proc /mnt/target/proc
    mount --bind /sys /mnt/target/sys
    mount --bind /run /mnt/target/run
    
    log "Target filesystem mounted"
}

# Install base system
install_base_system() {
    log "Installing base system..."
    
    # Use debootstrap to install base system
    debootstrap --arch=amd64 --variant=minbase bookworm /mnt/target http://deb.debian.org/debian/
    
    # Configure apt sources
    cat > /mnt/target/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
    
    # Configure hostname
    echo "$HOSTNAME" > /mnt/target/etc/hostname
    
    # Configure timezone
    ln -sf /usr/share/zoneinfo/$TIMEZONE /mnt/target/etc/localtime
    
    log "Base system installation complete"
}

# Install bootc and configure boot
install_bootc() {
    log "Installing bootc..."
    
    # Chroot into target and install bootc
    chroot /mnt/target bash -c "
        apt-get update
        apt-get install -y bootc
        bootc install-to-disk --target /dev/sda
    "
    
    log "Bootc installation complete"
}

# Create user account
create_user() {
    log "Creating user account: $USERNAME"
    
    chroot /mnt/target bash -c "
        useradd -m -s /bin/bash $USERNAME
        echo '$USERNAME ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/$USERNAME
        chmod 0440 /etc/sudoers.d/$USERNAME
    "
    
    log "User account created"
}

# Configure network
configure_network() {
    log "Configuring network..."
    
    # Enable systemd-networkd
    chroot /mnt/target bash -c "
        systemctl enable systemd-networkd
        systemctl enable systemd-resolved
    "
    
    # Create basic network configuration
    cat > /mnt/target/etc/systemd/network/20-wired.network << EOF
[Match]
Name=en*

[Network]
DHCP=yes
EOF
    
    log "Network configuration complete"
}

# Finalize installation
finalize_installation() {
    log "Finalizing installation..."
    
    # Generate initramfs
    chroot /mnt/target bash -c "
        update-initramfs -u -k all
    "
    
    # Unmount filesystems
    umount /mnt/target/run
    umount /mnt/target/sys
    umount /mnt/target/proc
    umount /mnt/target/dev
    umount /mnt/target/boot
    umount /mnt/target
    
    log "Installation complete!"
    log "You can now reboot to boot into your new Debian Atomic system."
}

# Main installation function
main() {
    log "Starting Debian Atomic Terminal Installer"
    
    check_root
    check_live_environment
    detect_target_device
    partition_device
    format_partitions
    mount_target
    install_base_system
    install_bootc
    create_user
    configure_network
    finalize_installation
    
    log "Installation completed successfully!"
}

# Run main function
main "$@" 