#!/bin/bash

set -e
shopt -s extglob

test=$1

case $test in
download/*)
        DISTDIR=
   ;;
*)
        DISTDIR=${top_srcdir}/testsuite/distdir
        RESTRICT=fetch
   ;;
esac

test -d ${top_builddir}/testsuite/$test || mkdir -p ${top_builddir}/testsuite/$test
cd ${top_builddir}/testsuite/$test

cp -f ${top_srcdir}/testsuite/$test/!(hints|filelists) .

DISTDIR=${DISTDIR} RESTRICT=${RESTRICT} ${top_builddir}/bin/cygport-inplace *.cygport clean get all

# compare hints
for hint in $(find -name \*.hint)
do
    # if CREATE_HINTS is set, create the expected hint file for use in future testing
    if [ -n ${CREATE_HINTS+x} ]
    then
        mkdir -p $(dirname ${top_srcdir}/testsuite/$test/hints/$hint)
        cp $hint ${top_srcdir}/testsuite/$test/hints/$hint
    else
        if [ -a ${top_srcdir}/testsuite/$test/hints/$hint ];
        then
            diff -u ${top_srcdir}/testsuite/$test/hints/$hint $hint
        else
            echo "can't verify hint $hint, as expected hint ${top_srcdir}/testsuite/$test/hints/$hint not found." >&2
            missing_hints=1
    fi
  fi
done

if [ -n "$missing_hints" ]
then
    exit 1
fi

# compare overall filelist
if [ -n ${CREATE_FILELISTS+x} ]
then
        cygport=$(echo *.cygport)
        ${top_builddir}/bin/cygport-inplace ${cygport} list >${top_srcdir}/testsuite/$test/${cygport/%.cygport/.list}
else
        diff -u ${CASE_INSENSITIVE:+-i} ${top_srcdir}/testsuite/$test/*.list <(${top_builddir}/bin/cygport-inplace *.cygport list)
fi

# compare package filelists
for archive in $(find -path '*/dist/*' -name '*.tar.*')
do
    filelist=${archive/%.tar*/.list}
    tar -atf ${archive} >${filelist}

    # if CREATE_FILELISTS is set, create the expected list file for use in future testing
    if [ -n ${CREATE_FILELISTS+x} ]
    then
        mkdir -p $(dirname ${top_srcdir}/testsuite/$test/filelists/$filelist)
        cp $filelist ${top_srcdir}/testsuite/$test/filelists/$filelist
    else
        if [ -a ${top_srcdir}/testsuite/$test/filelists/$filelist ];
        then
            diff -u ${CASE_INSENSITIVE:+-i} ${top_srcdir}/testsuite/$test/filelists/$filelist $filelist
        else
            echo "can't verify filelist $filelist, as expected filelist ${top_srcdir}/testsuite/$test/filelists/$filelist not found." >&2
            missing_filelists=1
        fi
    fi
done

if [ -n "$missing_filelists" ]
then
    exit 1
fi
