#!/bin/bash

readonly MODE='wipe'                            # total wipe of work dir preserving package cache
# readonly MODE='rebuild'                       # full update rebuild preserving work dir
# readonly MODE='tweak'                         # chroot customization tweaks only
readonly TARGET='dual'                          # dual-arch (default)
# readonly TARGET='i686'                        # i686 target only
# readonly TARGET='x86_64'                      # x86_64 target only
readonly EDITION='SystemD/CLI'                  # init/WM-DE pair (default)
# readonly EDITION='SystemD/LXDE'               # init/WM-DE pair
readonly CACHE=''                               # net-install (default)
# readonly CACHE='-O'                           # offline install
readonly VERSION="`date +%Y.%m.%d-%H.%M`-alpha" # ISO filename like: parabola-<EDITION>-<TARGET>-<VERSION>.iso


((`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' ]
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   ] && [ "$TARGET" == 'dual' -o "$TARGET" == 'i686'   ]
     then mkdir -p ./work/i686/root-image
          mv ./isorepo-i686   ./work/i686/root-image/isorepo
     fi
     if   [ -d ./isorepo-x86_64 ] && [ "$TARGET" == 'dual' -o "$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' ]
then rm -v ./work/build.make_*

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


CMD="./build.sh -v -E $EDITION -T $TARGET $CACHE -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
