#! /bin/bash -e

unset LANG

branch=master

while true ; do
  if [ "$1" = "--dist" -o "$1" = "--target" ] ; then
    dist="--target $2"
    shift
    shift
    continue
  fi

  if [ "$1" = "--branch" ] ; then
    branch=$2
    shift
    shift
    continue
  fi

  if [ "$1" = "--prepare" ] ; then
    prepare="$2"
    shift
    shift
    continue
  fi

  if [ "$1" = "--spec" ] ; then
    spec_opt="--spec $2"
    shift
    shift
    continue
  fi

  break
done

if [ -n "$1" ] ; then
  branch=$1
fi

git status
git checkout $branch
git pull

if [ -z "$prepare" ] ; then
  clean_target=clean
  grep -q -s distclean: Makefile* && clean_target=distclean

  make $clean_target

  if [ -d package ] ; then
    echo 'old archive files found!'
    exit 1
  fi

  make archive
else
  $prepare
fi

tobs $spec_opt $dist

if [ -z "$prepare" ] ; then
  make $clean_target
fi
