#!/bin/sh

set -e

VERSION=$(cat progs/altree | \
	sed -e '/our.*VERSION/s/.*qv(\([0-9.]\+\)).*/\1/p;d')

if [ "$VERSION" = "" ]; then
	echo "Unable to read current version. Aborting."
	exit 1
fi

FORCE=""

while [ $# != 0 ]; do
  case "$1" in
  --force)
    echo "--force enabled. Disabling sanity check..."
    FORCE=yes
    ;;
  --dry-run|-n)
    echo "--dry-run enabled. No real release will be done."
    DRYRUN="echo DRY-RUN: "
    ;;
  --)
    shift
    break
    ;;
  -*)
    echo "Unknown option $1"
    echo "Aborting"
    exit 1
    ;;
  *)
    break;
    ;;
  esac
  shift
done

echo "Creating version '$VERSION'"

set -x
[ -f Makefile ] || perl Makefile.PL
make Makefile || true
make realclean
make -C Documentation distclean
set +x

if [ "$(git status --short --untracked)" != "" ]; then
   echo "************************************"
   echo "* Not all files are commited/cleaned"
   echo "* Please correct before creating a release"
   echo "* (use 'git status --short --untracked' to look for problematic files)"
   echo "* (use 'git stash -a' to remove them temporarely)"
   echo "************************************"
   if [ "$FORCE" ]; then
     echo "* !!! WARNING: --force enabled : type 'ENTER to continue'"
     echo "************************************"
     read a
   else
     exit 1
   fi
fi
  
perl Makefile.PL

if [ "$(make distcheck 2>&1 1>/dev/null | grep -v "^No such file: META.yml$")" != "" ]; then
   echo "************************************"
   echo "* Not all files are in MANIFEST (or removed from it)"
   echo "* Please correct before creating a release"
   echo "* (use 'make distcheck' to look for problematic files"
   echo "************************************"
   if [ "$FORCE" ]; then
     echo "* !!! WARNING: --force enabled : type 'ENTER to continue'"
     echo "************************************"
     read a
   else
     exit 1
   fi
fi
  
make disttest
make dist

echo "************************************"
echo "* SUCCESS !"
echo "************************************"
echo "* Release created in altree-$VERSION.tar.gz"
echo "* Do not forget to create a git tag and push it"
echo "* You need to copy this file to the web site"
echo "* and tell Vince to update the debian package"
echo "************************************"



