#!/bin/bash

# set -euo pipefail
set -x

######################### Functions

function ok {
    echo -e "\033[0;32m[OK]\033[0m"
}

function nok {
    echo -e "\033[0;31mNOK : Abandon\033[0m"
    exit 1
}

# print argument to stdout in orange
function info {
    echo -e "\033[33m $@ \e[0m"

}

copy_function() {
    test -n "$(declare -f "$1")" || return
    eval "${_/$1/$2}"
}

rename_function() {
    copy_function "$@" || return
    unset -f "$1"
}

# Run initialisation checks
init_check() {

    # Checks the different folders isos and dev
    if ! [ -d $SCRIPTDIR"/isos" ]; then
        echo "isos folder does not exist"
        echo -e " > Creation of the folder\n"
        mkdir $SCRIPTDIR"/isos"
    fi
    if ! [ -d $SCRIPTDIR"/build_dir" ]; then
        echo "dev-sci folder does not exist"
        echo -e " > Creation of the folder\n"
        mkdir $SCRIPTDIR"/build_dir"
    fi

    if ! [ -f $DEBIAN_CD ]; then
        echo "No original ISO found, you should download one and set its path in conf.sh"
        exit 1
    fi
}

get_remote_udebs() {
    DIRDEV="build_dir"

    cd $DIRDEV/additionnal_udebs

    echo -e ""
    echo "Récuperation des udebs des dépôts Debian et de scibian/${MEDIA_VERSION}..."
    for udeb in $UDEBS $UDEBS_SCI; do
        echo $udeb
        if [ "$udeb" = di-utils_ ]; then
            continue
        fi

        if ! [ "$(
            ls ${udeb}_*.udeb 2> /dev/null
        )" ]; then
            sandboxed_apt download $udeb
        fi
    done
}

# Copy and interpolate template
_copy_and_interpolate_template() {
    if [ "$1" = INTERPOLATE ]; then
        INTERPOLATE=true
        shift
    fi

    src="templates.in/$1"
    dest="${DIRDEV}/$1"

    mkdir -p $(dirname "$dest".)

    SCI_REPO_HOST=$(cut -d/ -f3 <<< $SCI_REPO)
    SCI_REPO_DIR=/$(cut -d/ -f4- <<< $SCI_REPO)
    DEB_REPO_HOST=$(cut -d/ -f3 <<< $DEB_REPO)
    DEB_REPO_DIR=/$(cut -d/ -f4- <<< $DEB_REPO)
    if [ $(debian_codename_to_version $MEDIA_VERSION) -ge 12 ]; then
        DEB_COMPONENTS="main contrib non-free non-free-firmware"
    else
        DEB_COMPONENTS="main contrib non-free"
    fi
    if [ $(debian_codename_to_version $MEDIA_VERSION) -ge 13 ]; then
        SECURITY_CODENAME="${MEDIA_VERSION}-security"
    else
        SECURITY_CODENAME="${MEDIA_VERSION}/updates"
    fi

    cp "$src" "$dest"
    if [ "$INTERPOLATE" ]; then
        sed -i \
            -es/#SCIBIAN_CODENAME#/$MEDIA_VERSION/g \
            -es,#SECURITY_CODENAME#,$SECURITY_CODENAME,g \
            -es/#SCIBIAN_VERSION#/$(debian_codename_to_version $MEDIA_VERSION)/g \
            -es/#ISO_VERSION#/$isoversion/g \
            -es,#SCI_REPO#,$SCI_REPO,g \
            -es,#SCI_REPO_HOST#,$SCI_REPO_HOST,g \
            -es,#SCI_REPO_DIR#,$SCI_REPO_DIR,g \
            -es,#DEB_REPO#,$DEB_REPO,g \
            -es,#DEB_REPO_HOST#,$DEB_REPO_HOST,g \
            -es,#DEB_REPO_DIR#,$DEB_REPO_DIR,g \
            -e"s,#DEB_COMPONENTS#,$DEB_COMPONENTS,g" \
            "$dest"
    fi
}

interpolate_template() {
    _copy_and_interpolate_template INTERPOLATE "$1"
}

copy_template() {
    _copy_and_interpolate_template "$1"
}

# Set CD files
set_cd_template() {
    DIRDEV="build_dir"

    # Check if there is an absolute name set
    # If not set it as scibian_udeb version
    if [ ${#CD_VERSION} -eq 0 ]; then
        isoversion=$(date -u +%Y%m%d)
    else
        isoversion=$CD_VERSION
    fi

    # Clean up of the grub theme
    if [ -d "${DIRDEV}/grub/theme" ]; then
        rm -rf "${DIRDEV}/grub/theme"
    fi

    for i in "templates.in/grub/theme/"*; do
        interpolate_template ${i#templates.in/}
    done
    interpolate_template grub/grub.cfg

    # Clean up of the script
    if [ -f "${DIRDEV}/generate_scibian_img.sh" ]; then
        rm "${DIRDEV}/generate_scibian_img.sh"
    fi
    interpolate_template generate_scibian_img.sh

    interpolate_template apt-ftp.conf

    if [ -d "${DIRDEV}/isolinux" ]; then
        rm -rf "${DIRDEV}/isolinux"
    fi

    copy_template isolinux/splash.png

    interpolate_template preseed.cfg
}

# Determine ISO version
get_iso_version() {
    v=$(debian_codename_to_version $MEDIA_VERSION)
    v=${v:-XXX}
    echo $v-$(date +%Y%m%d)
}

# Setup APT sandbox
setup_apt_sandbox() {
    APTDIR=$1/apt
    rm -rf "${APTDIR}/etc/sources.list.d"
    mkdir -p "${APTDIR}/cache" "${APTDIR}/etc/preferences.d" "${APTDIR}/etc/sources.list.d" "${APTDIR}/state"
    ln -sf /etc/apt/trusted.gpg.d "${APTDIR}/etc/"

    cat > "${APTDIR}/etc/sources.list" << EOF
deb ${DEB_REPO_BUILD:-$DEB_REPO} ${MEDIA_VERSION} main main/debian-installer contrib non-free
deb ${SCI_REPO_BUILD:-$SCI_REPO} scibian$(debian_codename_to_version ${MEDIA_VERSION}) main main/debian-installer contrib non-free
EOF
    if [ "$USE_SCIBIAN_TEST" = true ]; then
        cat > "${APTDIR}/etc/sources.list.d/scibian-test.list" << EOF
deb ${SCI_REPO_BUILD:-$SCI_REPO} scibian$(debian_codename_to_version ${MEDIA_VERSION})-test main main/debian-installer contrib non-free
EOF
    fi
}

# Wrapper function to invoke our sandboxed APT
sandboxed_apt() {
    apt -oDir::State="${APTDIR}/state" -o Dir::Etc="${APTDIR}/etc" -oDir::Cache="${APTDIR}/cache" -oAcquire::Languages=none $*
}
