#!/usr/bin/env bash
set -euo pipefail

INPUT_ISO="debian-13.6.0-amd64-netinst.iso"
OUTPUT_ISO="debian-13.6.0-auto.iso"

WORKDIR="/opt/iso-build"
ISO_ROOT="${WORKDIR}/iso"
MOUNTPOINT="${WORKDIR}/mnt"

# ============================================================
# Cleanup
# ============================================================

cleanup() {
    if mountpoint -q "$MOUNTPOINT"; then
        umount "$MOUNTPOINT" || true
    fi
}

trap cleanup EXIT

echo
echo "==> Checking dependencies..."

for cmd in xorriso rsync mount umount mountpoint sha256sum; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "ERROR: '$cmd' is required."
        echo
        echo "Install with:"
        echo "  apt install xorriso rsync"
        exit 1
    fi
done


# ============================================================
# Check ISO
# ============================================================

if [[ ! -f "$INPUT_ISO" ]]; then
    echo "ERROR: ISO not found:"
    echo "  $(pwd)/$INPUT_ISO"
    exit 1
fi


# ============================================================
# Clean build directory
# ============================================================

echo
echo "==> Cleaning previous build..."

rm -rf "$WORKDIR"
rm -f "$OUTPUT_ISO"

mkdir -p "$ISO_ROOT"
mkdir -p "$MOUNTPOINT"


# ============================================================
# Mount original ISO
# ============================================================

echo
echo "==> Mounting original ISO..."

mount -o loop,ro "$INPUT_ISO" "$MOUNTPOINT"


# ============================================================
# Copy ISO
# ============================================================

echo
echo "==> Copying ISO contents..."

rsync -aH "$MOUNTPOINT/" "$ISO_ROOT/"


# ============================================================
# Unmount
# ============================================================

umount "$MOUNTPOINT"


# ============================================================
# Verify Debian installer files
# ============================================================

echo
echo "==> Checking Debian installer..."

if [[ ! -f "$ISO_ROOT/install.amd/vmlinuz" ]]; then
    echo "ERROR:"
    echo "  /install.amd/vmlinuz not found"
    exit 1
fi

if [[ ! -f "$ISO_ROOT/install.amd/initrd.gz" ]]; then
    echo "ERROR:"
    echo "  /install.amd/initrd.gz not found"
    exit 1
fi

echo "    vmlinuz: OK"
echo "    initrd:  OK"


# ============================================================
# Create preseed
# ============================================================

echo
echo "==> Creating preseed.cfg..."

cat > "$ISO_ROOT/preseed.cfg" <<'EOF'

### ============================================================
### Locale
### ============================================================

d-i debian-installer/locale string en_US.UTF-8
d-i keyboard-configuration/xkb-keymap select us


### ============================================================
### Network
### ============================================================

# Automatically select the first available network interface
d-i netcfg/choose_interface select auto

# Use DHCP
d-i netcfg/disable_autoconfig boolean false

d-i netcfg/get_hostname string debian
d-i netcfg/get_domain string


### ============================================================
### Mirror
### ============================================================

d-i mirror/country string manual
d-i mirror/http/hostname string deb.debian.org
d-i mirror/http/directory string /debian
d-i mirror/http/proxy string


### ============================================================
### Clock
### ============================================================

d-i clock-setup/utc boolean true
d-i time/zone string UTC
d-i clock-setup/ntp boolean true


### ============================================================
### Disk
### ============================================================

# WARNING:
#
# /dev/sda WILL BE COMPLETELY ERASED.
#

d-i partman-auto/disk string /dev/sda
d-i partman-auto/method string regular

# Use entire disk
d-i partman-auto/choose_recipe select atomic

# Confirm partitioning
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true


### ============================================================
### Root account
### ============================================================

d-i passwd/root-login boolean true

# CHANGE THIS!
d-i passwd/root-password password password123
d-i passwd/root-password-again password password123


### ============================================================
### Normal user
### ============================================================

# Do not create a normal user
d-i passwd/make-user boolean false


### ============================================================
### Packages
### ============================================================

tasksel tasksel/first multiselect standard, ssh-server

d-i pkgsel/include string openssh-server,curl,wget,vim

d-i pkgsel/upgrade select full-upgrade


### ============================================================
### GRUB
### ============================================================

d-i grub-installer/only_debian boolean true
d-i grub-installer/with_other_os boolean false

d-i grub-installer/bootdev string /dev/sda


### ============================================================
### Finish
### ============================================================

d-i finish-install/reboot_in_progress note

EOF


# ============================================================
# Configure GRUB
# ============================================================

if [[ -f "$ISO_ROOT/boot/grub/grub.cfg" ]]; then

    echo
    echo "==> Configuring GRUB..."

    cp "$ISO_ROOT/boot/grub/grub.cfg" \
       "$ISO_ROOT/boot/grub/grub.cfg.original"

    cat > "$ISO_ROOT/boot/grub/grub.cfg" <<'EOF'
set default=0
set timeout=1

menuentry "Debian 13 Automated Installation" {
    linux /install.amd/vmlinuz auto=true priority=critical preseed/file=/cdrom/preseed.cfg ---
    initrd /install.amd/initrd.gz
}
EOF

    echo "    GRUB configuration: OK"

else

    echo
    echo "WARNING: /boot/grub/grub.cfg not found"

fi


# ============================================================
# Configure ISOLINUX
# ============================================================

if [[ -f "$ISO_ROOT/isolinux/txt.cfg" ]]; then

    echo
    echo "==> Configuring ISOLINUX..."

    cp "$ISO_ROOT/isolinux/txt.cfg" \
       "$ISO_ROOT/isolinux/txt.cfg.original"

    cat > "$ISO_ROOT/isolinux/txt.cfg" <<'EOF'
default auto
timeout 10

label auto
    menu label ^Automated Debian installation
    kernel /install.amd/vmlinuz
    append auto=true priority=critical preseed/file=/cdrom/preseed.cfg initrd=/install.amd/initrd.gz ---
EOF

    echo "    ISOLINUX configuration: OK"

else

    echo
    echo "WARNING: /isolinux/txt.cfg not found"

fi


# ============================================================
# Create ISO
# ============================================================

echo
echo "==> Creating new ISO..."
echo
echo "    Input : $INPUT_ISO"
echo "    Output: $OUTPUT_ISO"
echo


xorriso \
    -indev "$INPUT_ISO" \
    -outdev "$OUTPUT_ISO" \
    -map "$ISO_ROOT/preseed.cfg" /preseed.cfg \
    -map "$ISO_ROOT/boot/grub/grub.cfg" /boot/grub/grub.cfg \
    -map "$ISO_ROOT/isolinux/txt.cfg" /isolinux/txt.cfg \
    -boot_image any replay \
    -commit


# ============================================================
# Check result
# ============================================================

if [[ ! -f "$OUTPUT_ISO" ]]; then

    echo
    echo "ERROR: ISO was not created."
    exit 1

fi


# ============================================================
# Verify
# ============================================================

echo
echo "==> ISO created successfully!"
echo

echo "File:"
ls -lh "$OUTPUT_ISO"

echo
echo "SHA256:"
sha256sum "$OUTPUT_ISO"

echo
echo "==> Boot information:"
echo

xorriso \
    -indev "$OUTPUT_ISO" \
    -report_el_torito plain

echo
echo "============================================================"
echo " SUCCESS"
echo "============================================================"
echo
echo "Created:"
echo "  $OUTPUT_ISO"
echo
echo "Installation:"
echo "  Disk     : /dev/sda"
echo "  Network  : DHCP"
echo "  Hostname : debian"
echo "  SSH      : enabled"
echo "  GRUB     : /dev/sda"
echo
echo "WARNING:"
echo "  /dev/sda will be completely erased!"
echo

