#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

make_folder () {
  rm -rf ./iso
  mkdir ./iso
}

find_src_iso() {
    find ./distr -name "ubuntu*.iso" -type f
}

find_1c_distr() {
    find ./distr -name "server64*.tar.gz" -type f
}

get_1c_ver() {
    basename $1 | rg -o -e "8_3_\d{2}_\d{4}" | cut -d'_' -f -4 --output-delimiter='.'
}

get_ubuntu_ver() {
    basename $1 | cut -d'-' -f 2
}

extract_iso() {
    xorriso -osirrox on -indev "$1" -extract / iso && chmod -R +w iso
}

install_config() {
    cp -R ./config/nocloud/ ./iso/nocloud/
}

validate_config() {
    yq ./config/nocloud/user-data > /dev/null && echo "config valid" || exit 1
}

install_1c() {
    mkdir -p ./iso/1c/install
    cp $1 ./iso/1c/install
}

config_grub() {
   find ./iso/boot/grub -type f -name '*.cfg' -exec sed -i 's|  ---| autoinstall ds=nocloud\\\;s=/cdrom/nocloud/  ---|g' {} +
}

fix_md5sums() {
    # The find will warn 'File system loop detected' and return non-zero exit status on the 'ubuntu' symlink to '.'
    # To avoid that, temporarily move it out of the way
    mv iso/ubuntu .
    (cd iso; find '!' -name "md5sum.txt" -follow -type f -exec "$(which md5sum)" {} \; > ../md5sum.txt)
    mv md5sum.txt iso/
    mv ubuntu iso 
}

get_iso_boot_config() {
    xorriso -indev $1 -report_el_torito as_mkisofs | sed -e "/\-V/s/ /_/g" -e "s/\-V_'/-V '/" | xargs
}

create_iso() {
    mkdir $(dirname $1) 2>/dev/null
    BOOT_CFG=$(get_iso_boot_config $2)
    xorriso -as mkisofs iso -r \
        $BOOT_CFG \
        -o $1 \
        -iso-level 3 -force-rr \
        -r -J -joliet-long -l
}

cleanup() {
    rm -rf ./iso
}

pushd $SCRIPT_DIR

SRC_ISO=$(find_src_iso)
DISTR_1C=$(find_1c_distr)
VER_1C=$(get_1c_ver $DISTR_1C)
VER_UBUNTU=$(get_ubuntu_ver $SRC_ISO)
OUT_ISO="./out/ubuntu-${VER_UBUNTU}-1c-${VER_1C}.iso"

validate_config
make_folder
extract_iso $SRC_ISO
install_config
config_grub
install_1c $DISTR_1C
fix_md5sums
create_iso $OUT_ISO $SRC_ISO
cleanup

echo $OUT_ISO

popd