#!/bin/sh

set -u
set -e
trap onexit INT
trap onexit TERM
trap onexit EXIT

TMPDIR=
SUDO=

onexit()
{
	if [ ! "$TMPDIR" = "" ]; then
		$SUDO rm -rf $TMPDIR
	fi
}

uid()
{
	id | cut -f2 -d = | cut -f1 -d \(;
}

safedirmove ()
{
	if [ "$1" = "$2" ]; then
		return 0
	fi
	if [ "$1" = "" -o ! -d "$1" ]; then
		echo safedirmove: source dir $1 is not valid
		return 1
	fi
	if [ "$2" = "" -o -e "$2" ]; then
		echo safedirmove: dest dir $2 is not valid
		return 1
	fi
	if [ "$3" = "" -o -e "$3" ]; then
		echo safedirmove: tmp dir $3 is not valid
		return 1
	fi
	mkdir -p $3
	mv $1/* $3/
	rmdir $1
	mkdir -p $2
	mv $3/* $2/
	rmdir $3
	return 0
}

makedeb()
{
	SUPPLEMENT=$1
	DIRNAME=$PACKAGE_NAME

	if [ $SUPPLEMENT = 1 ]; then
		PACKAGE_NAME=$PACKAGE_NAME\32
		DEBARCH=amd64
	fi

	umask 022
	rm -f $PACKAGE_NAME\_$VERSION\_$DEBARCH.deb
	TMPDIR=`mktemp -d /tmp/$PACKAGE_NAME-build.XXXXXX`
	mkdir $TMPDIR/DEBIAN

	if [ $SUPPLEMENT = 1 ]; then
		make install DESTDIR=$TMPDIR
		rm -rf $TMPDIR$BINDIR
		if [ "$DATADIR" != "$PREFIX" ]; then
			rm -rf $TMPDIR$DATADIR
		else
			rm -rf $TMPDIR$PREFIX/classes
		fi
		rm -rf $TMPDIR$DOCDIR
		rm -rf $TMPDIR$INCLUDEDIR
		rm -rf $TMPDIR$MANDIR
	else
		make install DESTDIR=$TMPDIR
		if [ "$PREFIX" = "@DEFAULT_CMAKE_INSTALL_PREFIX@" -a "$DOCDIR" = "@DEFAULT_CMAKE_INSTALL_PREFIX@/doc" ]; then
			safedirmove $TMPDIR/$DOCDIR $TMPDIR/usr/share/doc/$PACKAGE_NAME-$VERSION $TMPDIR/__tmpdoc
			ln -fs /usr/share/doc/$DIRNAME-$VERSION $TMPDIR$DOCDIR
		fi
	fi

	SIZE=`du -s $TMPDIR | cut -f1`
	(cat pkgscripts/deb-control | sed s/{__PKGNAME}/$PACKAGE_NAME/g \
		| sed s/{__ARCH}/$DEBARCH/g | sed s/{__SIZE}/$SIZE/g \
		> $TMPDIR/DEBIAN/control)

	/sbin/ldconfig -n $TMPDIR$LIBDIR

	$SUDO chown -Rh root:root $TMPDIR/*
	dpkg -b $TMPDIR $PACKAGE_NAME\_$VERSION\_$DEBARCH.deb
}

PACKAGE_NAME=@PKGNAME@
VERSION=@VERSION@
DEBARCH=@DEBARCH@
PREFIX=@CMAKE_INSTALL_PREFIX@
BINDIR=@BINDIR@
DATADIR=@DATADIR@
DOCDIR=@DOCDIR@
INCLUDEDIR=@INCLUDEDIR@
LIBDIR=@LIBDIR@
MANDIR=@MANDIR@

if [ ! `uid` -eq 0 ]; then
	SUDO=sudo
fi

makedeb 0
if [ "$DEBARCH" = "i386" ]; then makedeb 1; fi

exit
