#!/bin/sh

# Usage: From top source directory of polymake run
#
# % sh Packages/debian/snapshot-package.sh [-S] [-d]
#
# The -S option builds only a debian source package, and does not
# require polymake build dependencies in the current environment.

set -e

die () {
    echo $* >&2
    exit 1
}

tempdir=$(mktemp -d -p .. snapshot.XXXXXX)
debug=0

cleanup () {
    if [ "$debug" = 0 ]; then
	rm -rf $tempdir
	[ -f debian/.autogenerated ] && rm -r debian
    fi
}
trap cleanup EXIT;

if [ "$1" = "-S" ]; then
    source_only=1
    shift
else
    source_only=0
fi

if [ "$1" = "-d" ]; then
    debug=1
fi

if [ ! -f perllib/Polymake.pm ]; then
    die "This script must be run from the top level of the polymake source tree"
fi

cp -a Packages/debian .
touch ./debian/.autogenerated

# add polymake ignore files to dpkg-source options
./support/list_noexport_files . | sed 's,^./,tar-ignore ,' >> debian/source/options

# A less fragile way of doing this, without building polymake, would be welcome.

base_version=$(sed -n  -e 's/[;"]//g' -e "s/declare\s*[$]Version=//p"  perllib/Polymake.pm)

if [ -z $(command -v git) ]; then
    die "You need a git installation to run this script"
fi

commit=$(git describe --tags --match final_svn_commit |  sed -e s/final_svn_commit// -e s/-/+/g)

version="$base_version$commit"
echo Using version ${version}

if [ -z $(command -v dch) ]; then
    die "You need the 'dch' command from the package 'devscripts'"
fi

dch -v $version -m "git snapshot"

dpkg-buildpackage -S -uc -us

if [ -z $(command -v dcmd) ]; then
    die "You need the 'dcmd' command from the package 'devscripts'"
fi

if [ "$source_only" = 1 ]; then
    exit 0
fi;

( cd $tempdir
  dpkg-source -u -x ../polymake_$version.dsc
  cd polymake-$version
  dpkg-buildpackage -b -jauto -uc -us
  cd ..
  dcmd mv *.changes .. )
