#!/bin/bash
#   Copyright © 2015 Mattia Rizzolo <mattia@mapreri.org>
#
#   pbuilder -- personal Debian package builder
#
#   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
#
# module to satisfy build dependencies; aptitude flavor

set -e
set -x

export PBUILDER_PKGLIBDIR="${PBUILDER_PKGLIBDIR:-$PBUILDER_ROOT/usr/lib/pbuilder}"

. "$PBUILDER_PKGLIBDIR"/pbuilder-modules
. "$PBUILDER_PKGLIBDIR"/pbuilder-satisfydepends-funcs

function checkbuilddep_internal () {
    # FIXME this is broken until https://bugs.debian.org/754903 gets fixed

    # check whether apt is new enough
    if dpkg --compare-versions $($CHROOTEXEC dpkg-query -W -f '${Version}' apt) lt 1.1~exp1 ; then
        log "E: APT is not new enough to be used within this dependency resolver"
        log "E: Falling back on using the classic resolver"
        "$PBUILDER_PKGLIBDIR"/pbuilder-satisfydepncies-classic "$@"
        exit $?
    fi
    log "I: -> Attempting to satisfy build-dependencies"
    if [[ "$DEBIAN_CONTROL" = *.dsc ]]; then
        local DIR="./$DEBIAN_CONTROL"
    elif [[ "$DEBIAN_CONTROL" = *control ]]; then
        local DIR="${DEBIAN_CONTROL%/control}/../"
    else
        log 'E: Format of $DEBIAN_CONTROL not recognized ('"$DEBIAN_CONTROL"')'
        exit 1
    fi

    if [ "$BINARY_ARCH" = "yes" ]; then
        log "I: Not installing Build-Depends-Indep"
        APTGETOPT[${#APTGETOPT[@]}]='--arch-only'
    fi
    $CHROOTEXEC apt-get \
        -y \
        --no-install-recommends -o APT::Install-Recommends=false \
        "${APTGETOPT[@]}" \
        build-dep \
        "$DIR"
}


function print_help () {
    # print out help message
    cat <<EOF
pbuilder-satisfydepends -- satisfy dependencies

--help:        give help
--control:     specify control file (debian/control, *.dsc)
--chroot:      operate inside chroot
--binary-all:  include binary-all
--binary-arch: include binary-arch only
--echo:        echo mode, do nothing.

EOF
}

. "$PBUILDER_PKGLIBDIR"/pbuilder-satisfydepends-checkparams

