#!/bin/bash

set -e

if [ "$1" = "--help" ]
then
	cat <<__END__
init - Create an initial packaging

__END__
	$0 --manpage
	exit 0
fi


if [ "$1" = "--manpage" ]
then
cat <<'__END__'
Usage: dht init [-D distribution] Cabal-Pkg ...

This script will:

 * Query the package plan for the desired version number of CabalPkg.
 * Use `cabal unpack --pristine` to fetch the source into the right directory
 * Run cabal-debian --official to initialize the packaging.
 * Optimistically mark the package as ready for release
 * Commit this to git.

Please review the package afterwards, in particular `debian/copyright`.
__END__
	exit 0;
fi

if [ "$1" = "-D" ]
then
	dist="$2"
	shift
	shift
else
	dist=unstable
fi

if ! git diff-files --quiet -- "$@"
then
      echo "The git repository is not clean. Please fix that first!"
      exit 1
fi

if ! git diff-index --cached --quiet HEAD -- "$@"
then
      echo "WARNING: The git index is not clean, and will be amended!"
fi

if test -n "$(git ls-files --exclude-standard --others -- "$@")"
then
      echo "The git repository has untracked files. Please fix that first!"
      exit 1
fi


for cabal_name in "$@"
do
  cd "$(git rev-parse --show-toplevel)"

  version=$(grep "^$cabal_name " ../package-plan/packages.txt|cut -d\  -f2)

  if [ -z "$version" ]
  then
	echo "ERROR: could not detect version of $cabal_name to package"
	echo "Please update the package-plan first."
	continue
  fi

  source_name="haskell-$(echo "$cabal_name" | tr '[:upper:]' '[:lower:]')"

  if [ -d "p/$source_name" ]
  then
	echo "ERROR: p/$source_name already exists."
	continue
  fi

  cabal unpack --pristine "$cabal_name-$version"
  mv -v "$cabal_name-$version" "p/$source_name"

  cd "p/$source_name"
  dht cabal-debian

  git add .
  git commit -m "Initial packaging of $cabal_name-$version"
  dch -D $dist -r ''
  echo "Packaged $cabal_name-$version"
  git diff HEAD^..HEAD
done



