#!/bin/sh -e

# wrapper around dh_strip that generates packages with external debug symbols
#
# Author: Martin Pitt <martin.pitt@ubuntu.com>
# (C) 2006 Canonical Ltd.
#
#
# This program 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

DEBUG=1

if [ -x /usr/bin/dh_strip.pkg-create-dbgsym ]; then
    REAL_DHSTRIP=/usr/bin/dh_strip.pkg-create-dbgsym
elif [ "$0" != /usr/bin/dh_strip ]; then
    # called as "dh_strip" somewhere before /usr/bin in the PATH, e.g. from the
    # testsuite during package build
    REAL_DHSTRIP=/usr/bin/dh_strip
    if ! [ -x "$REAL_DHSTRIP" ]; then
        echo "FATAL: Can't run /usr/bin/dh_strip; is debhelper installed?" >&2
        exit 1
    fi
else
    echo "FATAL: Can't find the diverted original dh_strip and /usr/bin/dh_strip loops back to myself!" >&2
    exit 1
fi

HOSTARCH=`dpkg-architecture -qDEB_HOST_ARCH`

# print debug message
dbg() {
    [ -n "$DEBUG" ] || return 0
    echo "dh_strip debug symbol extraction: $@"
}

# return 0 if $1 is in the string list $2, otherwise return 1
in_list()
{
    echo "$2" | grep -q "\(^\|[[:space:]]\)$1\(\$\|[[:space:]]\)"
}   

if [ "$PKG_IGNORE_CURRENTLY_BUILDING" = 1 ]; then
    addtofiles="-a"
    dbg "enabling -a due to PKG_IGNORE_CURRENTLY_BUILDING = 1"
elif grep -qs '^Build-Debug-Symbols: yes$' /CurrentlyBuilding; then
    addtofiles="-a"
    dbg "enabling -a due to Build-Debug-Symbols: yes in /CurrentlyBuilding"
else
    # If sbuild hasn't explicitly told us to build debug symbols, we will
    # avoid doing so if this is a rebuild or PPA build.
    if grep -qs '^Suite: [a-z]*-autotest' /CurrentlyBuilding; then
        NO_PKG_MANGLE=1
        dbg "disabling for archive rebuild test"
    fi
    if grep -qs '^Purpose: PPA' /CurrentlyBuilding; then
        NO_PKG_MANGLE=1
        dbg "disabling for PPA build"
    fi

    # If /CurrentlyBuilding exists but Build-Debug-Symbols isn't set,
    # we don't know if Soyuz can handle ddebs yet. We don't want to
    # upload ddebs unless we really know that Soyuz can handle them, so
    # we tell pkg_create_dbgsym to avoid adding them to the changes
    # file.
    if [ -f /CurrentlyBuilding ]; then
        dbg "not enabling -a because /CurrentlyBuilding exists"
    else
        addtofiles="-a"
        dbg "enabling -a because /CurrentlyBuilding doesn't exist"
    fi
fi

if [ -n "$NO_PKG_MANGLE" ]; then
    dbg "not doing anything since NO_PKG_MANGLE is given"
    exec $REAL_DHSTRIP "$@"
    exit 0
fi

# get set of all architecture dependent packages from debian/control
packages=$(
    unset pkg
    sed -n 's/[[:space:]]*$//; s/^\(Package\|Architecture\):[[:space:]]*\(.\+\)/\1 \2/p' debian/control | while read key val; do
	if [ "$key" = Package ]; then
	    [ -z "$pkg" ] || {
		echo "Error: Package: and Architecture: do not alternate in debian/control" >&2
		exit 1
	    }
	    pkg="$val"
	fi
	if [ "$key" = Architecture ]; then
	    [ -n "$pkg" ] || {
		echo "Error: Package: and Architecture: do not alternate in debian/control" >&2
		exit 1
	    }
	    for arch in $val; do
		if dpkg-architecture -a"$HOSTARCH" -i"$arch"; then
		    printf "$pkg "
		    break
		fi
	    done
	    unset pkg
	fi
    done 
)
dbg "all non-arch-all packages for this build platform $HOSTARCH: $packages"

# parse command line to determine set of packages to act on
for p in $DH_OPTIONS $@; do
    if [ -n "$next_arg_is_xopt" ]; then
        xopts="$xopts -X$p"
        unset next_arg_is_xopt
        continue
    fi

    p=${p#-O}
    case "$p" in
	-i|--indep)
	    unset actpkgs
	    optsel=1
	    ;;
	-a|--arch|-s|--same-arch)
	    actpkgs="$packages"
	    optsel=1
	    ;;
	-p*|--package=*)
	    pkg=${p#--package=}
	    pkg=${pkg#-p}
	    if ! in_list "$pkg" "$actpkgs" && in_list "$pkg" "$packages"; then
		actpkgs="$pkg $actpkgs"
	    fi
	    optsel=1
	    ;;
	-N*|--no-package=*)
	    pkg=${p#--no-package=}
	    pkg=${pkg#-N}
	    if ! in_list "$pkg" "$ignorepkgs"; then
		ignorepkgs="$pkg $ignorepkgs"
	    fi
	    ;;
	--dbg-package*)
	    dbg "not adding gnu debuglinks since --dbg-package is given"
	    nodebuglink=1
	    ;;
	-k|--keep-debug)
	    dbg "not adding gnu debuglinks since --keep-debug is given"
	    nodebuglink=1
	    ;;
	-P*|--tmpdir=*)
	    pkgdirarg=${p#--tmpdir=}
	    pkgdirarg=${pkgdirarg#-P}
	    dbg "-P/--tmpdir option: setting temporary package dir to $pkgdirarg"
            ;;
        -X)
            next_arg_is_xopt=1
            ;;
        -X*)
            xopts="$xopts $p"
            ;;
    esac
done

[ -n "$optsel" ] || actpkgs="$packages"

dbg "packages to act on: $actpkgs"
dbg "ignored packages: $ignorepkgs"

# check for debhelper compat level 1
dhcompat1=1
if [ -e debian/compat ]; then
    if [ "`cat debian/compat`" != 1 ]; then
	unset dhcompat1
    fi
fi
if grep -q '^[[:space:]]*\(export[[:space:]]*\)\?DH_COMPAT[[:space:]]*:\?=[[:space:]]*[2-9]\>' debian/rules; then
    unset dhcompat1
elif grep -q '^[[:space:]]*\(export[[:space:]]*\)\?DH_COMPAT[[:space:]]*:\?=[[:space:]]*1\>' debian/rules; then
    dhcompat1=1
fi

if [ -n "$dhcompat1" ]; then
    first_control_pkg="`grep -m 1 ^Package debian/control | cut -f2- -d\ `"
    dbg "using obsolete debhelper compat mode 1"
fi

# process all packages
for p in $actpkgs; do
    if in_list "$p" "$ignorepkgs" ||
	echo $p | grep -Eq -- '-(dbg|dbgsym)$' ; then
	continue
    fi

    if [ -n "$pkgdirarg" ]; then
	pkgdir="$pkgdirarg"
    elif [ -n "$dhcompat1" -a $p = "$first_control_pkg" ]; then
	pkgdir=debian/tmp
    else
	pkgdir=debian/$p
    fi

    # if the package calls dh_strip, we assume/require it also calls
    # dh_gencontrol; so call in "don't build .ddeb package file" mode so that
    # dh_gencontrol can update the version
    pkg_create_dbgsym -B $addtofiles $xopts $p $pkgdir "$nodebuglink"
done

exec $REAL_DHSTRIP "$@"
