#!/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 and exit if not
if [[ $EUID -ne 0 ]]; then
    echo "Not running as root. Exiting..."
    exit 1
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
echo "Updating system and installing dependencies..."
apt-get update -y && apt-get install -y wget
check_command

# Create necessary directories
echo "Creating directories..."
mkdir -p /opt/samba/Windows_Server_2019/
check_command

# Download Windows_Server_2019_Eval ISO
if [ ! -f /opt/samba/isos/Windows_Server_2019_Eval.iso ]; then
	echo "Downloading Windows Server 2019 Eval ISO..."
	wget https://cdn.as212934.net/windows/server/Evaluation/Windows_Server_2019_Eval.iso -O /opt/samba/isos/Windows_Server_2019_Eval.iso
	check_command
fi

# Mount the ISO and copy contents
echo "Mounting ISO and copying files..."
mkdir -p /mnt/iso
mount -o loop /opt/samba/isos/Windows_Server_2019_Eval.iso /mnt/iso
check_command

cp -r /mnt/iso/* /opt/samba/Windows_Server_2019/
check_command

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

rm -rf /mnt/iso
check_command

echo "Script completed successfully!"
