#! /bin/bash -xe

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
# This script is maintained at https://github.com/openSUSE/linuxrc-devtools
#
# If you're in another project, this is just a copy.
# You may update it to the latest version from time to time...
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

PATH=$PATH:utils

while true ; do
  if [ "$1" = "--name" ] ; then
    PACKAGE_NAME="$2"
    shift
    shift
    continue
  fi

  if [ "$1" = "--set-name" ] ; then
    PACKAGE_NAME="$2"
    set_name=1
    shift
    shift
    continue
  fi

  break
done

if [ -z "$PACKAGE_NAME" ] ; then
  PACKAGE_NAME=$(git config --get remote.origin.url | perl -pe 's#^.*/|\.git$##g')
fi

if [ -z "$PACKAGE_NAME" ] ; then
  echo no package name set
  exit 1
fi

VERSION=`git2log --version VERSION ; cat VERSION`
PACKAGE_PREFIX=$PACKAGE_NAME-$VERSION

mkdir -p package
rm -f package/*.tar.xz package/*.changes

extra_files=VERSION

git2log --changelog --format obs package/$PACKAGE_NAME.changes

if [ -f changelog ] || grep -q ^changelog: Makefile ; then
  git2log --changelog changelog
  extra_files="$extra_files changelog"
fi

if [ "$set_name" = 1 ] ; then
  echo "$PACKAGE_NAME" > PACKAGE_NAME
  extra_files="$extra_files PACKAGE_NAME"
fi

if [ ! -d .git ] ; then
  echo no git repo
  exit 1
fi

git archive --prefix=$PACKAGE_PREFIX/ HEAD > package/$PACKAGE_PREFIX.tar

tar -r -f package/$PACKAGE_PREFIX.tar \
  --mode=0664 --owner=root --group=root \
  --mtime="`git show -s --format=%ci`" \
  --transform="s:^:$PACKAGE_PREFIX/:" $extra_files
xz -f package/$PACKAGE_PREFIX.tar

if [ "$set_name" = 1 ] ; then
  rm -f PACKAGE_NAME
fi
