#!/bin/bash

dist=lolita-el7

pass=0
declare -a failures
declare -a oldfailures

[ -x /usr/bin/repomanage ] && cleanup="/usr/bin/repomanage --old --space" \
                           || cleanup="/usr/bin/dnf repomanage --old --space"

usage() {
cat >&2 << EOF_USAGE
Usage: $0 [-t <target>] specfile1 … specfileX
<target>: target environment

Examples:
$0 *\.spec
$0 -t lolita-rawhide foo.spec
EOF_USAGE
exit 1
}

rebuild() {
pass=$((pass + 1))
echo "◾◾◾◾Build pass $pass…"
for spec in "${oldfailures[@]}" ; do
  echo "◾◾◾Processing $spec…"
  srpm=$(LANG=C rpmbuild -bs $spec | sed 's+Wrote: ++g')
  [ -r "$srpm" ] && \
    $mock $srpm && \
    install -vp -m 644 /var/lib/mock/$dist/result/*\.rpm /srv/rpm/$dist
  if [ $? -ne 0 ] ; then
    failures+=( "${spec}" )
  else
    oldpackages=$($cleanup /srv/rpm/$dist 2>/dev/null)
    [ -n "$oldpackages" ] && rm $oldpackages
    createrepo_c --update --xz --no-database /srv/rpm/$dist
    sync
  fi
  echo "Done processing $spec"
done
}

if ! options=$(getopt -n $0 -o ht: -l help,target: -- "$@")
then
    # something went wrong, getopt will put out an error message for us
    exit 2
fi

eval set -- "$options"

while [ $# -gt 0 ] ; do
  case $1 in
    -h|--help)    usage ;;
    -t|--target)  dist="$2" ; shift;;
    (--)          shift; break;;
    (-*)          echo "$0: error - unrecognized option $1" >&2; exit 3;;
    (*)           break;;
  esac
  shift
done

fullspecs=( $* )

mock="/usr/bin/mock -r $dist --with=bootstrap"
oldfailures=()
failures=( "${fullspecs[@]}" )
echo "◾◾◾◾◾Bootstraping…"

until [ ${#failures[@]} -eq 0 ] || [ ${#failures[@]} -eq ${#oldfailures[@]} ] ; do
  oldfailures=( "${failures[@]}" )
  failures=()
  rebuild
done

if [ ${#failures[@]} -eq 0 ] ; then
  mock="/usr/bin/mock -r $dist"
  oldfailures=()
  failures=( "${fullspecs[@]}" )
  echo "◾◾◾◾◾Standard builds…"
  until [ ${#failures[@]} -eq 0 ] || [ ${#failures[@]} -eq ${#oldfailures[@]} ] ; do
    oldfailures=( "${failures[@]}" )
    failures=()
    rebuild
  done
fi

echo "The rebuild required $pass passes."
[ ${#failures[@]} -ne 0  ] && echo "Build failures: ${failures[@]}"
