#!/bin/bash

MAKE="make JOBS=12"
# MAKE="echo"
logfile=build.log
STAGE=""

homedir=/home/mjhammel/src/ximba/raspberrypi3/bld/buildroot-2020.02.4/output/target/home
mydir=${homedir}/mjhammel
sysroot=${mydir}/src/ximba/raspberrypi4/bld/buildroot-2020.02.4.bld/staging/arm-buildroot-linux-gnueabihf/sysroot

hfound=0
mfound=0
sfound=0

log()
{
    echo "$1" >> ${logfile}
}

log_start()
{
    if [[ -n "${STAGE}" ]]; then
        echo "Finished ${STAGE}" >> ${logfile}
    fi
    echo "Starting $1" >> ${logfile}
    STAGE="$1"
}

doQuit()
{
    if  [[ ${sfound} -eq 1 ]] && 
        [[ ${sfound} -eq 1 ]] && 
        [[ ${sfound} -eq 1 ]]; then
        log "The culprit is in the ${STAGE} build."
        exit 0
    fi
}

checkDir()
{
    if [[ ${hfound} -eq 0 ]] && [[ -d ${homedir} ]]; then
        log "${STAGE} created output/target/home directory."
        hfound=1
    fi
    if [[ ${mfound} -eq 0 ]] && [[ -d ${mydir} ]]; then
        log "${STAGE} created output/target/home/mjhammel directory."
        mfound=1
    fi
    if [[ ${sfound} -eq 0 ]] && [[ -d ${sysroot} ]]; then
        log "${STAGE} created sysroot directory."
        sfound=1
    fi
    doQuit
}

rm -f ${logfile}
# log_start xcc && ${MAKE} xcc && checkDir
# log_start xcc-pkg && ${MAKE} xcc-pkg && checkDir
# log_start rpifw && ${MAKE} rpifw && checkDir
# log_start rpifw-pkg && ${MAKE} rpifw-pkg && checkDir
# log_start kernel && ${MAKE} kernel && checkDir
# log_start kernel-pkg && ${MAKE} kernel-pkg && checkDir
# log_start gles && ${MAKE} gles && checkDir
# log_start gles-pkg && ${MAKE} gles-pkg && checkDir
# log_start busybox && ${MAKE} busybox && checkDir
# log_start busybox-pkg && ${MAKE} busybox-pkg && checkDir
# log_start buildroot && ${MAKE} buildroot && checkDir
# log_start buildroot-pkg && ${MAKE} buildroot-pkg && checkDir

BUILDROOT_SRCDIR=/home/mjhammel/src/ximba/raspberrypi3/src/../bld/buildroot-2020.02.4
BUILDROOT_BLDDIR=/home/mjhammel/src/ximba/raspberrypi3/src/../bld/buildroot-2020.02.4.bld
BUILDROOT_ARCDIR=/home/mjhammel/src/ximba/raspberrypi3/src/../archive/buildroot
BUILDROOT_T=buildroot

log_start buildroot-clobber && ${MAKE} buildroot-clobber && checkDir
log_start buildroot-init && ${MAKE} buildroot-init && checkDir
mkdir -p ${BUILDROOT_BLDDIR}/images ${BUILDROOT_ARCDIR}
log_start buildroot-clobber && ${MAKE} ${BUILDROOT_T}-preconfig && checkDir
log_start buildroot-config && ${MAKE} ${BUILDROOT_T}-config && checkDir
log_start buildroot-oldconfig && pushd ${BUILDROOT_SRCDIR} && ${MAKE} oldconfig && checkDir && popd
log_start buildroot-legal-info && ${MAKE} ${BUILDROOT_T}-legal-info && checkDir
log_start buildroot && pushd ${BUILDROOT_SRCDIR} && \
    ${MAKE} LD_LIBRARY_PATH= BUSYBOX_CONFIG=${BUILDROOT_SRCDIR}/.busybox_config && checkDir && \
    popd
log_start buildroot-rpitools && ${MAKE} ${BUILDROOT_T}-rpitools && checkDir
