#!/bin/bash

# Exit immediately if a command fails, and report failed pipeline commands.
set -eo pipefail

# Function to check command success and exit if failure occurs
check_command() {
    if [[ $? -ne 0 ]]; then
        echo "Error: Command failed."
        exit 1
    fi
}

# Ensure the script is being run as root or use sudo
if [[ $EUID -ne 0 ]]; then
    echo "Not running as root. Using sudo..."
    SUDO="sudo"
else
    SUDO=""
fi

# Ensure the hostname does not contain "dci"
if [[ "$(hostname)" =~ dci ]]; then
    echo "This script cannot run on a server with hostname containing 'dci'."
    exit 1
fi

# Install dependencies and Docker
echo "Updating system and installing dependencies..."
$SUDO apt-get update -y && $SUDO apt-get install -y ca-certificates curl
check_command

# Install Docker GPG key and setup repository
echo "Setting up Docker repository..."
$SUDO install -m 0755 -d /etc/apt/keyrings
$SUDO curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
check_command

$SUDO chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | $SUDO tee /etc/apt/sources.list.d/docker.list > /dev/null
check_command

# Update APT and install Docker packages
$SUDO apt-get update -y
$SUDO apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
check_command

# Create Docker Compose file for netbootxyz
echo "Creating Docker Compose file..."
$SUDO cat << EOF > /root/docker-compose.yml
services:
  netbootxyz:
    image: lscr.io/linuxserver/netbootxyz:latest
    container_name: netbootxyz
    environment:
      - PUID=0
      - PGID=0
    volumes:
      - /root/Netboot-xyz/config:/config
      - /root/Netboot-xyz/assets:/assets
    ports:
      - 3000:3000
      - 8080:80 # optional
    restart: unless-stopped
EOF
check_command

# Create necessary directories
echo "Creating directories..."
$SUDO mkdir -p /root/Netboot-xyz/{assets,config} /root/Netboot-xyz/assets/WinPE/x64/
check_command

# Download WinPE ISO
echo "Downloading WinPE ISO..."
$SUDO wget https://cdn.as212934.net/Windows/WinPE_amd64.iso -O /root/WinPE_amd64.iso
check_command

# Mount the ISO and copy contents
echo "Mounting ISO and copying files..."
$SUDO mkdir -p /mnt/iso
$SUDO mount -o loop /root/WinPE_amd64.iso /mnt/iso
check_command

$SUDO cp -r /mnt/iso/* /root/Netboot-xyz/assets/WinPE/x64/
check_command

# Clean up ISO and mount
echo "Unmounting ISO and cleaning up..."
$SUDO umount /mnt/iso
check_command

$SUDO rm -f /root/WinPE_amd64.iso
$SUDO rm -rf /mnt/iso
check_command

# Run Docker Compose to start netbootxyz container
echo "Starting Docker container..."
$SUDO docker compose -f /root/docker-compose.yml up -d
check_command

echo "Script completed successfully!"
