#!/bin/bash
#set -x

echo ""
echo "${0}: Started binary ISO image build at $(date -R)"
echo ""

. ./_build_env

are_you_root

check_build_target "$@"

check_live_build_version

WMLIVEBASEDIR=$(pwd)

export TIMESTAMP=$(date +%Y-%m-%d-%H%M)

for ARCH in $ARCHLIST
do
    WMLIVEPKGLIST="build-config/package-lists/kernel.list.binary"
    rm -vf ${WMLIVEPKGLIST} && \
    grep -v ^# ${WMLIVEPKGLIST}_${ARCH} > ${WMLIVEPKGLIST}
    cp -v ${WMLIVEPKGLIST}_${ARCH} build-config/includes.chroot/root/

    export ISONAME=wmlive_"$TIMESTAMP-"$ARCH""

    if [ "$(echo "$ARCH" | cut -d \- -f1)" = "amd64" ]
    then
        PROGARCH="linux-x86_64" && echo PROGARCH is defined as $PROGARCH
    elif [ "$(echo "$ARCH" | cut -d \- -f1)" = "i386" ]
    then
        PROGARCH="linux-i686" && echo PROGARCH is defined as $PROGARCH
    fi

    if [ ! "$PROGARCH" = "" ]
    then
        PROGARCHIVEDIR="$WMLIVEBASEDIR/build-config/wmlive-opt/$PROGARCH"
        PROGEXTRASDIR="$WMLIVEBASEDIR/build-config/includes.binary/"$(echo "$ARCH" | cut -d \- -f1)"/custom"
        cp -av $PROGARCHIVEDIR/* "$PROGEXTRASDIR"
    fi

    cd $WMLIVEBASEDIR

    copy_wmlive_source

    if [ -d wmlive-"$ARCH" ]
    then
        cd wmlive-"$ARCH" && time lb binary 2>&1 | tee binary-"$TIMESTAMP".log && \
        if [ -f live-image-"$ARCH".hybrid.iso ]
        then
            mv -v live-image-"$ARCH".hybrid.iso "$ISONAME".iso
            mv -v build-"$TIMESTAMP".log "$ISONAME".log
            mv -v live-image-"$ARCH".packages "$ISONAME".list
            ls -l "$ISONAME".*
        fi
        if [ -s "$ISONAME".iso ]
        then
            echo lb clean
        else
            echo -e "\n  Something went wrong:"
            echo "  Please check the log file,"
            echo "  fix the root cause and"
            echo -e "  then try again.\n"
        fi
        cd $WMLIVEBASEDIR
    fi
done
echo ""
echo "${0}: Finished binary ISO image build at $(date -R)"
echo ""
