#!/bin/bash -e

# override nerve-gpb's /usr/local/bin/build.sh to be able to postpone
# mk-build-deps *AFTER* generation on debian/control et al.

DOCKER_SOCK=${DOCKER_SOCK:-/var/run/docker.sock}

if [[ -e $DOCKER_SOCK ]]; then
    DOCKER_GID=$(stat -c '%g' $DOCKER_SOCK)

    # add group with --quiet, in case a group with that gid already exists
    addgroup --system --gid=${DOCKER_GID} --quiet gbp-docker

    # get the group name of the group we just maybe created
    DOCKER_GROUP=$(getent group ${DOCKER_GID} | cut -d: -f1)
fi

# Install build dependencies -> postponed to postexport
# needed to have a recent database for getting available kernel images
apt-get update

if [[ -n ${UID} && -n ${GID} ]]; then
    addgroup --gid ${GID} gbp
    adduser --uid=${UID} --gid=${GID} --disabled-password --gecos '' gbp

    # allow mk-build-deps in postexport script
    echo "gbp ALL=(ALL) NOPASSWD:/usr/bin/mk-build-deps" >> /etc/sudoers

    if [[ -n "${DOCKER_GROUP}" ]]; then
        adduser --quiet gbp ${DOCKER_GROUP}
    fi

    sudo -E -u gbp gbp.sh "$@"
else
    echo '####################################################################################'
    echo "# WARNING: building package as root user. It's recommended you run this image with #"
    echo '#         docker run -e UID=`id -u` -e GID=`id -g` ....                            #'
    echo '####################################################################################'
    gbp.sh "$@"
fi
