#!/bin/bash

test "$1" = "--verbose" && { VERBOSE=true ; shift ; }
test "$1" = "--batchmode" && { BATCHMODE=true ; shift ; }
DIR_TO_CHECK=$1
DESTINATIONDIR=$2
test -n "$DIR_TO_CHECK" || DIR_TO_CHECK=`pwd`
HELPERS_DIR="/usr/lib/obs/service/source_validators/helpers"
$HELPERS_DIR/check_input_filename "$DIR_TO_CHECK" || exit 1

test -z "$DESTINATIONDIR" -a -d "$DIR_TO_CHECK/.osc" && DESTINATIONDIR="$DIR_TO_CHECK/.osc"

RETURN=0
test "$VERBOSE" = true && echo -n "- checking for stale or missing changes "
SPECLIST=`/usr/lib/obs/service/source_validators/helpers/output_versions -q -m $DIR_TO_CHECK | sed -e "s@ .*@@" | sort -u`

test -n "$SPECLIST" && {
for i in $SPECLIST ; do
    test -f $DIR_TO_CHECK/$i.changes || {
	echo "WARNING: $i.changes does not exist. This package can not be submitted to openSUSE product projects."
	exit 0
    }
done
# check for stale .changes files
for i in $DIR_TO_CHECK/*.changes ; do
    test -f $i || continue
    N=`basename $i .changes`
    OKAY=0
    for pack in $SPECLIST ; do
        test "$pack" = "$N" && OKAY=1
    done
    if test $OKAY = 0 ; then
	if ! grep -q "^Source[0-9]*:.*$N.changes" $DIR_TO_CHECK/*.spec ; then
	    echo "ERROR: $(basename $i) not a subpackage, please remove"
	    RETURN=1
	fi
    fi
done
}
test "$VERBOSE" = true && echo done


exit $RETURN
