#!/bin/bash
# Make custom ISO image for partner.
# Arguments:
#   the major version to make ISOs for (ex, 6.5)
#   key of space to make ISO for
#   salted root password
#   timezone
#   debian mirror hostname
#   dns servers, comma seperated
#   if the cert for the management server is valid
#
# © 2020, Multapplied Networks, Inc.

# Space key is a mandatory argument
if [ "$#" -ne 8 ] ; then
    echo "usage: $0 version space_key salted_root_password timezone debian_mirror_hostname dns_servers valid_mgmt_cert use_legacy_ifname" 1>&2
    exit 1
fi

VERSION="$1"
SPACE_KEY="$2"
SALTED_ROOT_PASSWORD="$3"
TIMEZONE="$4"
DEBIAN_MIRROR="$5"
DNS_SERVERS="$6"
VALID_MGMT_SERVER_CERT="$7"
USE_LEGACY_IFNAME="$8"
MGMT_NAME=$(grep mgmt_server_url /etc/bondingadmin/bondingadmin.conf | awk '{print $3}')

if [ "$(whoami)" != "bondingadmin" ] ; then
    sudo -u bondingadmin /usr/sbin/make-debian-10-iso "$@"
    exit $?
fi

should_create_iso=$(ba should_create_iso "$SPACE_KEY" > /dev/null 2>&1)
if [ "$?" -ne 0 ] ; then
    echo "ISOs can't be created for this space."
    exit 1
fi

set -eou pipefail

# Load arguments
ISO_INPUT_DIR="/var/lib/bondingadmin/base-isos"
ISO_OUTPUT_DIR="/var/lib/bondingadmin/isos/$SPACE_KEY"
BONDINGADMIN_CONF="/etc/bondingadmin/bondingadmin.conf"

if [ -e "$ISO_OUTPUT_DIR/bonding-debian*.iso" ] ; then
    echo -n "Cleaning output directory: "
    rm "$ISO_OUTPUT_DIR/bonding-debian*.iso"
elif [[ ! -d "$ISO_OUTPUT_DIR" ]] ; then
    echo -n "Creating output directory: "
    mkdir -p $ISO_OUTPUT_DIR
fi
echo "done."

TMPDIR=$(mktemp -d)
trap 'rm -rf $TMPDIR' EXIT

base_iso="$ISO_INPUT_DIR/bonding-debian.x86_64-$VERSION.install.iso"
if [[ ! -f $base_iso ]] ; then
    echo "$base_iso does not exist"
    exit 0
fi

test -f /etc/default/bondingadmin/make-iso && . /etc/default/bondingadmin/make-iso

function prep_base_iso_dir() {
    _base_iso=$1; shift

    base_iso_name=$(basename $_base_iso)
    base_iso_filename=${base_iso_name%.*}
    base_iso_unpack_dir="$TMPDIR/$base_iso_filename"

    # Clear and re-create ISO directory
    mkdir -p $base_iso_unpack_dir
    /usr/bin/bsdtar -C $base_iso_unpack_dir -xf $base_iso
    chmod -R u+rw $base_iso_unpack_dir

    echo $base_iso_unpack_dir
}


function modify_iso() {
    iso_dir=$1; shift
    for grub_cfg in $iso_dir/EFI/BOOT/grub.cfg $iso_dir/boot/grub/grub.cfg ; do
        SALTED_ROOT_PASSWORD=$(echo $SALTED_ROOT_PASSWORD | sed -r 's/[$]+/\\$/g')
        if [ "${USE_LEGACY_IFNAME}" = "True" ] ; then
            sed -i "s|local_options=.*|local_options=\"password=$SALTED_ROOT_PASSWORD timezone=$TIMEZONE management=$MGMT_NAME valid_mgmt_cert=$VALID_MGMT_SERVER_CERT mirror=$DEBIAN_MIRROR nameservers=$DNS_SERVERS net.ifnames=0\"|g" $grub_cfg
        else
            sed -i "s|local_options=.*|local_options=\"password=$SALTED_ROOT_PASSWORD timezone=$TIMEZONE management=$MGMT_NAME valid_mgmt_cert=$VALID_MGMT_SERVER_CERT mirror=$DEBIAN_MIRROR nameservers=$DNS_SERVERS\"|g" $grub_cfg
        fi
        cat $grub_cfg
    done
}

function make_uefi() {
    # Modern, with UEFI and BIOS support
    directory=$1; shift
    iso_name=$1; shift
    target_iso_path="$TMPDIR/$iso_name"

    # Rebuild the EFI boot image
    efi_loader="$directory/efi_loader"
    qemu-img create $efi_loader 20M
    /usr/sbin/mkdosfs -n BOOT $efi_loader
    mcopy -Do -s -i $efi_loader "$directory/EFI" ::

    /usr/bin/xorriso \
        -application_id 0x9e0cd9ed \
        -volid INSTALL \
        -joliet on \
        -padding 0 \
        -outdev $target_iso_path \
        -map $directory / \
        -chmod 0755 / -- \
        -boot_image grub bin_path=boot/x86_64/loader/eltorito.img \
        -boot_image grub grub2_mbr=$directory/boot/x86_64/loader/boot_hybrid.img \
        -boot_image grub grub2_boot_info=on \
        -boot_image any partition_offset=16 \
        -boot_image any cat_path=boot/x86_64/boot.catalog \
        -boot_image any cat_hidden=on \
        -boot_image any boot_info_table=on \
        -boot_image any platform_id=0x00 \
        -boot_image any emul_type=no_emulation -boot_image any load_size=2048 \
        -append_partition 2 0xef $efi_loader\
        -boot_image any next \
        -boot_image any efi_path=--interval:appended_partition_2:all:: \
        -boot_image any platform_id=0xef \
        -boot_image any emul_type=no_emulation

    [ ! -d $ISO_OUTPUT_DIR ] && mkdir -p $ISO_OUTPUT_DIR
    cp -f $target_iso_path $ISO_OUTPUT_DIR
}


echo -n "Making ISO: unpack"
iso_unpacked_dir=$(prep_base_iso_dir $base_iso)
echo -n " modify"
modify_iso $iso_unpacked_dir
echo -n " repack"
make_uefi $iso_unpacked_dir bonding-debian.x86_64-$VERSION-$SPACE_KEY-install.iso
echo "."
