#!/bin/bash

me="$(id -u)"
if [ "$me" -ne "0" ]; then
    echo "I need to be run as root"
    exit
fi

if [ ! -x $(which xorriso) ]; then
    echo "xorriso not found!"
    echo "please install it."
    exit
fi

if [ "$#" -lt "1" ]; then
    echo "Usage: ${0%*/} <src_dir> [isohdpfx.bin]"
    exit 201
fi

ISOSTR="Debian 11 amd64 fmw net"
HYBRIDMBR="/usr/lib/ISOLINUX/isohdpfx.bin"

SRCDIR="$1"
ISOTARGET="${SRCDIR%%/*}.iso"

if [ ! -f ${HYBRIDMBR} ]; then
    echo "Hybrid MBR not found!"
    echo "Install isolinux or extract the MBR from a Debian CD as:"
    echo "dd if=debian-x.y.z-amd64-netinst.iso  of=isohdpfx.bin bs=1 count=432"
    echo "If you manually extracted it, pass the file as the second arg."
    exit 202
fi

# Extract the iso
#xorriso -osirrox on -indev debian-10.8.0-amd64-netinst.iso -extract / debian-10.8.0-amd64-netinst-nf-fmw

xorriso \
    -as mkisofs \
    -r -V "${ISOSTR}" \
    -J -R -joliet-long -cache-inodes \
    -isohybrid-mbr ${HYBRIDMBR} \
    -b isolinux/isolinux.bin \
    -c isolinux/boot.cat \
    -boot-load-size 4 \
    -boot-info-table \
    -no-emul-boot \
    -eltorito-alt-boot \
    -e boot/grub/efi.img \
    -no-emul-boot \
    -isohybrid-gpt-basdat \
    -isohybrid-apm-hfsplus \
    -o $ISOTARGET \
    $SRCDIR && echo "Created $ISOTARGET"
