#!/bin/bash

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

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

argsparse_use_option variant: "Variant" default:""
argsparse_use_option mirror: "Mirror" default:""
argsparse_use_option use-scibian-test "Use scibian test"
argsparse_use_option debian-version: "Major Debian version" type:int default:$(dpkg -s scibian-cd | awk '/^Version:/ { print $2}' | cut -d. -f1)

argsparse_parse_options "$@"

set -x

VARIANT="${program_options[variant]}"
DEB_REPO="${program_options[mirror]}"
DEBVERSION="${program_options['debian-version']}"
if argsparse_is_option_set use-scibian-test; then
    USE_SCIBIAN_TEST=true
else
    USE_SCIBIAN_TEST=false
fi

set -euo pipefail

usage() {
    echo -n "scibian-cd <init|udebs|build"
    declare -F \
        | sort \
        | grep "^declare -f scibiancd_" \
        | sed -e "s/^declare -f scibiancd_//" \
        | while read f; do
            echo -n "|$f"
        done
    echo ">"
    echo -e "Build a bootable ISO for Scibian"
    echo -e "Options: "
    echo -e "  init <directory>: Set a folder as a Scibian CD project"
    echo -e "  udebs: Get the requested udebs specified in config"
    echo -e "  build: Generate the final ISO"
    echo -e "  pki-id: Show the CD pki login/password"
    echo -e "  pki-test: test the CD pki login/password"
}

is_scibian-cd_env() {
    [ ! -d "./isos" ] && errorline "Missing 'isos' folder: Does not seem to be a Scibian CD folder" && exit 1
    [ ! -d "./build_dir" ] && errorline "Missing 'build_dir' folder: Does not seem to be a Scibian CD folder" && exit 1
    [ ! -f "config" ] && errorline "Missing 'config' file: File is required" && exit 1
    infoline "scibian-cd environment detected"
}

export SCRIPTDIR=$(pwd)

read_common

case "${program_params[0]}" in
init)
    env_folder="${program_params[1]}"
    if [ ! -d $env_folder ]; then
        infoline "Folder $env_folder does not seem to exist\n"
        set +u
        read -p "Do you want to create it ? [y/N] " answser
        if [ $answer="y" ]; then
            mkdir -p $env_folder
            successline "Environment created"
        else
            exit 1
        fi
        set -u

        cp -r /usr/share/scibian/scibian-cd/base_files/* $env_folder
        if [ "$VARIANT" ] && [ -d /usr/share/scibian/scibian-cd/base_files-$VARIANT ]; then
            cp -r /usr/share/scibian/scibian-cd/base_files-$VARIANT/* $env_folder
        fi
        mkdir ${env_folder}/isos/
        mkdir -p ${env_folder}/build_dir/

        cd $env_folder
        is_scibian-cd_env
        read_config
        # setup_apt_sandbox $env_folder
        # sandboxed_apt update
    else
        infoline "Folder $env_folder seems to exist\n"
    fi
    infoline "You need to add a debian iso to the ${env_folder}/isos/ and to customize the config file\n"

    ;;
udebs)
    is_scibian-cd_env
    read_config
    setup_apt_sandbox $(pwd)

    sandboxed_apt update

    # Download all udebs required
    get_remote_udebs
    ;;
build)
    is_scibian-cd_env
    read_config
    setup_apt_sandbox $(pwd)

    sandboxed_apt update

    # Need to call maj-scibian-iso
    isoversion=$(get_iso_version)
    set_cd_template
    echo -e "\nISO Generation"
    echo "DEBIAN_CD="$DEBIAN_CD
    echo "isoversion="$isoversion
    echo "Build directory = $DIRDEV"
    echo -e "\nConstruction de l'ISO Scibian :  \n(logs: $DIRDEV/iso-build.log ) .. "
    infoline "Commande à exectuer depuis build_dir/ :\n"
    cmd="bash -x ./generate_scibian_img.sh -i $DEBIAN_CD -o $DIRISOS/scibian_$isoversion.iso -m $DEB_REPO --variant=$VARIANT --debian-version=${DEBVERSION}"
    echo "$cmd >> iso-build.log"
    cd $DIRDEV
    $cmd | tee -a iso-build.log

    if [ $? -eq "0" ]; then
        successline "L'ISO généré est disponible ici : $DIRISOS/scibian_$isoversion.iso"
    else
        errorline "Erreur lors de la génération du cd"
    fi

    ;;
help)
    usage
    ;;
*)
    f="scibiancd_${program_params[0]}"
    t=$(type -t "$f") || true
    if [ "$t" = "function" ]; then
        $f
    else
        usage
        exit 1
    fi
    ;;
esac
