#!/bin/bash -e

ORIGINAL_ARGUMENTS=$@
BUILD="false"
while [ $# -gt 0 ]; do
    case "$1" in
        --build|-b)
            BUILD="true"
            shift ;;
        *)
            shift ;;
    esac
done

if [ "$BUILD" = "true" ]; then
    if grep -qs '^Suite: [a-z]*-autotest' ${CURRENTLY_BUILDING_PATH:-"/CurrentlyBuilding"}; then
        NO_PKG_MANGLE=1
        echo "INFO: Disabling pkgbinarymangler for archive rebuild test"
    fi
    if grep -q '^Section: partner' debian/control; then
        NO_PKG_MANGLE=1
        echo "INFO: Disabling pkgbinarymangler for partner packages"
    fi
    if [ -z "$NO_PKG_MANGLE" ]; then
        if which pkgsanitychecks >/dev/null; then
            pkgsanitychecks $ORIGINAL_ARGUMENTS
        else
            echo "ERROR: dpkg-deb is diverted, but pkgsanitychecks is not executable; please check your configuration"
            exit 1
        fi
        if which pkgstriptranslations >/dev/null; then
            pkgstriptranslations
        else
            echo "ERROR: dpkg-deb is diverted, but pkgstriptranslations is not executable; please check your configuration"
            exit 1
        fi
        if which pkgmaintainermangler >/dev/null; then
            pkgmaintainermangler $ORIGINAL_ARGUMENTS
        else
            echo "ERROR: dpkg-deb is diverted, but pkgmaintainermangler is not executable; please check your configuration"
            exit 1
        fi
    else
        echo "WARNING: not running pkgbinarymangler for this package, as requested"
    fi
fi

exec -a "$0" dpkg-deb.pkgbinarymangler $ORIGINAL_ARGUMENTS
