#!/bin/bash

readonly MODE='wipe'
# readonly ISO_TARGET='dual'     # (default)
readonly ISO_TARGET='i686'
# readonly ISO_TARGET='x86_64'
# readonly EDITION='SystemD/CLI' # (default)
readonly EDITION='SystemD/LXDE'
# readonly INSTALL_TYPE=''       # net-install (default)
readonly INSTALL_TYPE='-O'   # offline install
readonly VERSION="`date +%Y.%m.%d-%H.%M`-alpha"


((`id -u`)) && echo "This script must be run with root privileges." && exit

while mount | grep $PWD/work/; do umount $(mount | grep --max-count=1 $PWD/work/) ; sleep 1 ; done ;

if   [ "$MODE" == 'wipe' ] # total wipe (preserving package cache)
then [ -d ./work/i686/root-image/isorepo   ] && mv ./work/i686/root-image/isorepo   ./isorepo-i686
     [ -d ./work/x86_64/root-image/isorepo ] && mv ./work/x86_64/root-image/isorepo ./isorepo-x86_64

     rm -rf ./work/ 2> /dev/null

     if   [ -d ./isorepo-i686   ] && [ "$ISO_TARGET" == 'dual' -o "$ISO_TARGET" == 'i686'   ]
     then mkdir -p ./work/i686/root-image
          mv ./isorepo-i686   ./work/i686/root-image/isorepo
     fi
     if   [ -d ./isorepo-x86_64 ] && [ "$ISO_TARGET" == 'dual' -o "$ISO_TARGET" == 'x86_64' ]
     then mkdir -p ./work/x86_64/root-image
          mv ./isorepo-x86_64 ./work/x86_64/root-image/isorepo
     fi

elif [ "$MODE" == 'rebuild' ] # full rebuild
then rm -v ./work/build.make_*

elif [ "$MODE" == 'tweak' ] # tweaks only
then rm work/build.make_customize_root_image_$ISO_TARGET \
        work/build.make_prepare_$ISO_TARGET              \
        work/build.make_iso*                             2> /dev/null
fi


CMD="./build.sh -v -E $EDITION -T $ISO_TARGET $INSTALL_TYPE -V $VERSION"
if   ${CMD}
then echo "success" ; rm ./continue.sh 2> /dev/null
else echo -e "failure - continue with: ./continue.sh"
     echo -e "#!/bin/bash\n${CMD}" > ./continue.sh
     chmod a+x ./continue.sh
fi
