#!/bin/sh -e

TESTSOURCES="dhtest dhtest.doublestrip dhtest.samename dhtest.substvars dhtest.whitespace dhtest.nostrip dhtest.noargs dhtest.archspecific dhtest.tmpdirarg dhtest.compat1 dhtest.compat1override dhtest.compatenvvar dhtest.dbg dhtest.dbg.buildid dhtest.dbg2 dhtest.dbg3 dhtest.pydbg dhtest.dbg.empty dhtest.versionoverride dhtest.customdbgsym cdbstest manualtest"

print_result() {
    if [ -n "$fail" ]; then
	echo "FAIL: $1"
	echo "Output:"
	echo '---------------------------------------------------------------------'
	echo "$2"
	echo '---------------------------------------------------------------------'
	echo Please remove testsuite.tmp after examination
	exit 1
    else
	echo "PASS: $1"
    fi
    unset fail
    return 0
}

# Arguments: <command> <test suite description>
# execute given command, pass test if it exits successfully, fail test if not.
# In the latter case, print command output and abort
check_command() {
    out=`$1 2>&1` || fail=1	
    print_result "$2" "$out"
}

# Arguments: <application deb> <corresponding dbgsym deb>
check_pkg_pair() {
    deb="$1"
    ddeb="$2"
    mkdir unpacked
    dpkg -x $deb unpacked
    dpkg -x $ddeb unpacked

    # gdb looks for the absolute path of the executable
    mkdir -p unpacked/usr/lib/debug/`pwd`
    ln -s `pwd`/unpacked/usr/lib/debug unpacked/usr/lib/debug/`pwd`/unpacked

    for bin in unpacked/usr/bin/*; do
	# check for debuglink section
	objdump -j .gnu_debuglink -s $bin | grep -q .gnu_debuglink || fail=1
	print_result "$bin has .gnu_debuglink section" "`objdump -j .gnu_debuglink -s $bin`"

	# check for good backtrace
	bt=`gdb --batch -ex "set debug-file-directory unpacked/usr/lib/debug" -ex "file $bin" -ex run -ex 'bt'`
	echo "$bt" | grep -q 'g (x=1, y=42)' || fail=1
	print_result "$bin: $deb and $ddeb produce good backtrace" "$bt"
    done
    rm -rf unpacked

    # check that Multi-Arch: field is the same
    PKG_MA=`dpkg -I $deb | grep '^[[:space:]]*Multi-Arch:'` || :
    DDEB_MA=`dpkg -I $ddeb | grep '^[[:space:]]*Multi-Arch:'` || :
    [ "$PKG_MA" = "$DDEB_MA" ] || fail=1
    print_result "$deb: Multi-Arch: field is identical"

    # should not copy enhances
    dpkg -I $ddeb | grep -q '^[[:space:]]*Enhances:' && fail=1 || :
    print_result "$ddeb: No Enhances: field"
}

ROOTDIR=$(readlink -f `dirname $0`/..)
cd $ROOTDIR/tests
ORIGDIR=`pwd`
mkdir testsuite.tmp
cd testsuite.tmp

for s in $TESTSOURCES; do
    echo "===== $s ====="
    rm -rf *

    # copy source package into test directory
    cp -r ../$s .

    # build it
    cd $s
    check_command "env -u NO_PKG_MANGLE PATH=$ROOTDIR:$PATH PKG_IGNORE_CURRENTLY_BUILDING=1 fakeroot dpkg-buildpackage -us -uc -b" "Building source package $s"
    # clean it
    check_command "fakeroot debian/rules clean" "Cleaning source package $s"
    # debhelper compat 1 leaves debhelper.log behind, work around
    rm -f debian/debhelper.log
    SRCVERSION=`dpkg-parsechangelog -SVersion`
    cd ..
    # check for leftovers
    check_command "diff -ur $s ../$s" "No leftover files after cleaning $s"

    if [ "${s%customdbgsym*}" != "$s" ]; then
        echo "skipping ddeb check for custom -dbgsym test"
        continue
    fi

    dbg_pkgs=''

    for deb in *.deb; do
	pkg=`echo $deb|cut -d_ -f1`
	version=`echo $deb|cut -d_ -f2`
	version=${version#*:} # strip off epoch
	arch=`echo ${deb%.deb}|cut -d_ -f3`

	if echo $pkg | grep -q -- '^python'; then
            # python packages are special, ignore them
            check_command "test ! -f ${pkg}-dbgsym_${version}_${arch}.ddeb" "No dbgsym ddeb for $deb"
            continue
	elif echo $pkg | grep -q -- '-dbg$' && dpkg -c "$deb" | grep -q ./usr/lib/debug/; then
            dbg_pkgs="$dbg_pkgs $pkg"
            # verify that the -dbg works
	    check_pkg_pair "${pkg%-dbg}_${version}_${arch}.deb" "${pkg}_${version}_${arch}.deb"
	else
	    if dpkg -c $deb | grep -q usr/bin && ! echo $deb | grep -q nostrip; then
		check_command "test -f ${pkg}-dbgsym_${version}_${arch}.ddeb" "dbgsym ddeb for $deb exists"
	    else
		check_command "test ! -f ${pkg}-dbgsym_${version}_${arch}.ddeb" "No dbgsym ddeb for $deb"
	    fi
	fi
    done

    for ddeb in *.ddeb; do
        INFO=`dpkg -I $ddeb`
        VERSION=`echo "$INFO" | grep "^[[:space:]]*Version:" | cut -f3 -d' '`
        DBGSYMNAME=`echo $ddeb|cut -d_ -f1`
        PKGNAME=${DBGSYMNAME%-dbgsym}
        PKGDEB=`echo $ddeb | sed 's/-dbgsym_/_/; s/\.ddeb/.deb/'`
        DEBINFO=`dpkg -I $PKGDEB`
        DEBVERSION=`echo "$DEBINFO" | grep "^[[:space:]]*Version:" | cut -f3 -d' '`
        PKGLIST=`dpkg -c $ddeb`
        PKGLIST=`echo "$PKGLIST" | grep -v ' \./$'` || true

        echo "$INFO" | egrep -q '^[[:space:]]*(Pre-Depends|Recommends|Suggests|Provides|Replaces|Conflicts|Breaks|Essential):' && fail=1 || true
        print_result "$ddeb has other dependencies stripped" "$INFO"

        if [ "$DEBVERSION" = "$SRCVERSION" ]; then
            echo "$INFO" | grep -q "^[[:space:]]*Source: $s\$" || fail=1
        else
            echo "$INFO" | grep -q "^[[:space:]]*Source: $s ($SRCVERSION)\$" || fail=1
        fi
        print_result "$ddeb has a correct Source field" "$INFO"

        echo "$INFO" | grep -A1 "^[[:space:]]*Section: [a-zA-Z0-0]\+\$" | tail -n1 | grep -q '^[[:space:]]*Priority: '|| fail=1
        print_result "$ddeb has a correct Section field" "$INFO"

        echo "$INFO" | grep -q "^[[:space:]]*Description: debug symbols for package $PKGNAME\$" || fail=1
        print_result "$ddeb has a correct (short) Description field" "$INFO"

        [ "$VERSION" = "$DEBVERSION" ] || fail=1
        print_result "$ddeb has correct binary version $DEBVERSION" "$VERSION"

        if [ -n "$dbg_pkgs" ]; then
            # if we already have a -dbg, the -dbgsym packages should be empty dummy
            # packages that merely depend on the -dbg packages; we already
            # asserted above that the -dbg package works
            for c in $dbg_pkgs; do
                echo "$INFO" | grep -q "^[[:space:]]*Depends: .*$c" || fail=1
                print_result "$ddeb depends on $c" "$INFO"
            done

            [ -n "$PKGLIST" ] && fail=1 || true
            print_result "$ddeb does not have any files" "$PKGLIST"
        else
            # without -dbg, check that our -dbgsyms work and have all other
            # dependency fields stripped
            echo "$PKGLIST" | grep -q './usr/lib/debug/' || fail=1
            print_result "$ddeb has /usr/lib/debug dir" "$PKGLIST"

            echo "$INFO" | grep -q "^[[:space:]]*Depends: $PKGNAME (= $VERSION)\$" || fail=1
            print_result "$ddeb has a correct Depends field" "$INFO"
            check_pkg_pair $PKGDEB $ddeb
        fi
    done
done

cd "$ORIGDIR"
rm -r testsuite.tmp
