#!/bin/bash
set -e

builddir='build'
next=false

for foo in "$@"
do
  if [[ $foo == '--build-dir' ]]
  then
    next=true
  elif $next
  then
    builddir="$foo"
    # Normally --build-dir should be passed only once, it will be accepted by
    # bauerbill multiple times and the last one will be used, so simply set
    # next to false instead of breaking here.
    next=false
  fi
done

scripts=(download.sh build.sh clean.sh)

for s in "${scripts[@]}"
do
  spath="$builddir/$s"
  if [[ -e $spath ]]
  then
    rm -- "$spath"
  fi
done

if [[ -n $SUDO_USER ]]
then
#   if [[ -d $builddir ]]
#   then
#     sudo chown -R "$SUDO_USER:$(id -gn "$SUDO_USER")" "$builddir"
#   fi
  cmd_prefix=(sudo -u "$SUDO_USER")
else
  cmd_prefix=()
fi

# The command prefix ensures that SUDO_USER is correctly passed to bauerbill
# even if bb-wrapper is run as root. Bauerbill uses that variable to chown the
# generated scripts.
"${cmd_prefix[@]}" sudo bauerbill "$@"


if [[ -d $builddir ]]
then
  pushd "$builddir"
  for s in "${scripts[@]}"
  do
    if [[ -x $s ]]
    then
      # Ensure that the scripts are run as the non-root user.
      "${cmd_prefix[@]}"  ./"$s"
    fi
  done
  popd
fi

