#!/bin/sh
set -e
#  Copyright (C) 2008 Neil Williams <codehelp@debian.org>
#
#  This package is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROG=em_newer

. /usr/lib/emdebian-tools/empbuilderlib

function usagehelp () {
    # print out help message
    cat <<EOF
$PROG - emdebian target package check for current versions
version $OURVERSION

Syntax: $PROG [OPTIONS] [COMMAND]
EOF
}

ARCH=` perl -MDebian::DpkgCross -e '&read_config; print &get_architecture;'`

while [ -n "$1" ]; do
case "$1" in
	--help|-h|-\?|--version)
		usagehelp
		exit;
	;;
	-a|--arch)
		shift
		ARCH=$1
		# chomp the argument to --arch
		shift
	;;
	*)
		echo "Unrecognised option: $1"
		echo
		usagehelp
		exit;
	;;
esac
done

PACKAGE=$1
DIR=`perl -MEmdebian::Tools -MConfig::Auto -e 'print &get_dpkg_cross_dir;'`
SUITE=`perl -MEmdebian::Tools -MConfig::Auto -e 'print &get_targetsuite;'`

if [ -z "$PACKAGE" ]; then
	echo "No package specified, checking for debian/changelog"
	PACKAGE=`parsechangelog | grep Source | cut -d' ' -f2`
fi

echo "Checking package: $PACKAGE"

DEBIAN=`apt-cache -o Apt::Architecture=$ARCH -o APT::Get::List-Cleanup=off \
-o Apt::Install-Recommends=false -o Dir=$DIR -o Dir::Etc=$DIR \
-o Dir::Etc::SourceList=sources.$SUITE -o Dir::State=$SUITE \
-o Dir::State::Status=$DIR/status -o Dir::Cache=$SUITE \
showsrc $PACKAGE | egrep "^Version" | cut -d' ' -f2 | sed -e 's/ //'`

EMDEBIAN=`apt-cache -o Apt::Architecture=$ARCH -o APT::Get::List-Cleanup=off \
-o Apt::Install-Recommends=false -o Dir=$DIR/host -o Dir::Etc=$DIR/host \
-o Dir::Etc::SourceList=sources.compare.$SUITE -o Dir::State=$SUITE \
-o Dir::State::Status=$DIR/host/status -o Dir::Cache=$SUITE showsrc $PACKAGE | \
egrep "^Version" | cut -d' ' -f2 | sed -e 's/em[0-9]//' | sed -e 's/ //'`

if [ -z "$EMDEBIAN" ]; then
	echo "Debian version $DEBIAN is not in Emdebian - upload needed."
	exit
fi
set +e
dpkg --compare-versions $DEBIAN '=' $EMDEBIAN
RES=`echo $?`
if [ $RES -eq 0 ]; then
	echo "Debian $DEBIAN is the same version as Emdebian"
	exit
fi

dpkg --compare-versions $DEBIAN '>' $EMDEBIAN
RES=`echo $?`
if [ $RES -eq 0 ]; then
	echo "Debian version $DEBIAN is newer than Emdebian $EMDEBIAN - upload needed."
else
	echo "Debian $DEBIAN not newer than $EMDEBIAN."
fi
