#! /bin/bash -e

unset LANG

branch=master

while true ; do
  if [ "$1" = "--target" ] ; then
    target="--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

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

  if [ "$1" = "--no-tag" ] ; then
    tag_opt="--no-tag"
    shift
    continue
  fi

  break
done

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 $target $spec_opt $obs_opt $tag_opt

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