#!/bin/bash
# If you want to run this script without using scibian-cd, you have to source beforehand the config file

source /usr/lib/scibian/scibian-cd/functions.sh

. /usr/share/bash-argsparse/argsparse.sh

set -euo pipefail
set -x

argsparse_use_option =input-iso: "input ISO" mandatory
argsparse_use_option =output-iso: "output ISO" default:"$(pwd)/scibian.iso"
argsparse_use_option =release: "Release" default:""
argsparse_use_option =mirror: "Mirror" mandatory
argsparse_use_option passthrough "Passthrough"
argsparse_use_option variant: "Variant" default:""
argsparse_use_option debian-version: mandatory

build_dir=$(pwd)

echo "Analyzing start options\n"
argsparse_parse_options "$@"

input_iso="${program_options['input-iso']}"
output_iso="${program_options['output-iso']}"
release="${program_options['release']}"
DEB_REPO="${program_options['mirror']}"
VARIANT="${program_options['variant']}"
DEBVERSION="${program_options['debian-version']}"
if argsparse_is_option_set passthrough; then
    passthrough=yes
else
    passthrough=no
fi

read_config

MEDIA_VERSION=$(debian_version_to_codename $DEBVERSION)
release=$MEDIA_VERSION

echo "Check for scibian keyrings\n"
for i in $SCIBIAN_KEYRING; do
    if [ -f "$i" ]; then
        echo "$i found"
    else
        echo "$i not found"
        echo -en "['\u2717']"
        echo ""
        exit 1
    fi
done

[[ -f "$input_iso" ]] || {
    echo "input-iso '${input_iso}': no such file"
    exit 1
}
[[ -w "$(dirname "$output_iso")" ]] || {
    echo "$(dirname "$output_iso"): not writable for output iso"
    exit 1
}

tmpdir="$(mktemp -d "$(pwd)/cd_build_$(date +%Y%m%d%H%M%S)_XXXXXX")"
echo "Création du dossier temporaire $tmpdir pour la décompression\n"
cd "$tmpdir"

# Extract disk files and give writable rights
echo "Extract original debian dist\n"
xorriso -indev "$input_iso" -osirrox on -extract . cd
chmod -R u+rw cd
iso_root=${tmpdir}/cd

# some files on the original CD are hardlinks but xorriso fails to see that
# if we don't hardlink identical files we will loose a lot of CD place
hardlink cd

# extract hybrid mbr from iso
# this is a hack, but it is better than using the boot sector from
# syslinux-common which may be a different version
echo "Extracting MBR for Debian ISO\n"
isolinux_mbr="$(pwd)/mbr.bin"
dd if="$input_iso" of="$isolinux_mbr" bs=446 count=1

# customize disk files unless passthrough
if ! [ "$passthrough" = "yes" ]; then

    # copie des udebs
    echo "Copying udebs\n"
    for udeb in ${build_dir}/additionnal_udebs/*.udeb; do
        echo "Dealing with $(basename ${udeb})"
        if ! stat -t "$udeb" > /dev/null; then
            echo "[×]"
            echo ""
            break
        fi
        udeb_filename="${udeb#${build_dir}/additionnal_udebs/}"
        pkgname="$(echo "$udeb_filename" | sed 's/_[^_]\+_[^_]\+.udeb//')"
        first_letter="${udeb_filename:0:1}"
        udeb_dir="cd/pool/main/${first_letter}"
        # remove any existing versions of the same udeb
        echo "Removing previously present version of ${pkgname}"
        find $iso_root/pool/ -name "${pkgname}_*.udeb" -type f -delete
        mkdir -p "$udeb_dir"
        cp "$udeb" "$udeb_dir"
        echo "$pkgname" >> $iso_root/.disk/udeb_include
        echo -e "\n--"
    done

    if [ $CLEAN_UP = "TRUE" ]; then
        echo "Removing useless .deb and useless kernel\n"
        find $iso_root/pool/ -name "*.deb" -type f -delete
        rm -rf $iso_root/install.amd/xen/
        rm -rf $iso_root/install.amd/gtk/
        rm -rf $iso_root/doc/
    fi

    echo "Création des archives APT\n"
    echo "$(pwd)"
    #  apt-ftparchive generate ../config-udeb
    #  apt-ftparchive generate ../config-deb
    cd $iso_root
    echo "Generation du fichier Packages\n"
    apt-ftparchive -c ${build_dir}/apt-ftp.conf packages pool/ > dists/${release}/main/debian-installer/binary-amd64/Packages
    cd ${iso_root}/dists/${release}/main/debian-installer/binary-amd64/
    rm -f Packages.gz
    gzip -k Packages
    cat > Release << EOF
Archive: stable
Origin: Debian
Label: Debian
Version: 10.5
Acquire-By-Hash: yes
Component: main
Architecture: amd64
EOF
    cd ${iso_root}/dists/${release}/
    echo "Generation du fichier Release\n"
    apt-ftparchive -c ${build_dir}/apt-ftp.conf release . > Release
    cd ${tmpdir}

    #  apt-ftparchive -c ../config-rel release "cd/dists/${release}" > "cd/dists/${release}/Release"

    # conf isolinux
    cp -r ../isolinux/* ${iso_root}/isolinux
    cp -r ../grub/* ${iso_root}/boot/grub
    cp ../preseed.cfg ${iso_root}

    set -x
    echo "Copie des trousseaux GPG des dépots\n"
    for i in $SCIBIAN_KEYRING; do
        # gpg --no-default-keyring --keyring ${iso_root}/scibian-archive-keyring.gpg --import $i
        fakeroot apt-key --keyring ${iso_root}/scibian-archive-keyring.gpg add - < $i
    done
    cp ${iso_root}/scibian-archive-keyring.gpg ${iso_root}/calibre-archive-keyring.gpg

    # Empeche une installation sans réseau
    rm -f ${iso_root}/.disk/base_installable

fi

echo "ISO repackaging\n"
# generate output iso
xorriso -as mkisofs \
    -r \
    -V 'Scibian_#ISO_VERSION#' \
    -o "$output_iso" \
    -J -isohybrid-mbr "$isolinux_mbr" \
    -J -joliet-long -cache-inodes \
    -b isolinux/isolinux.bin -c isolinux/boot.cat \
    -no-emul-boot -boot-load-size 4 -boot-info-table \
    -eltorito-alt-boot \
    -e boot/grub/efi.img -no-emul-boot \
    -isohybrid-gpt-basdat -isohybrid-apm-hfsplus --hardlinks ${iso_root}
