#!/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
apt-get install -y python3-nerve-build-helpers

# determine commit-ish the build is triggered for
DIST=${DIST:-$(cat /etc/nerve_release)}
[[ "buster bullseye bookworm sid" =~ (^|[[:space:]])${DIST}($|[[:space:]]) ]] && AT="master" || AT=${DIST}
# Derive all required kernel versions from images and rtvm blobs
VERSIONLISTFILE=$(mktemp)
nerve-get-packages --at ${AT} $(nerve-get-images --at ${AT}) | \
	grep -E 'linux-image-[0-9]+\.[0-9]+\.[0-9]+-' | \
	sed -e 's/linux-image-\([0-9\.]*-[^-]*-.*\)/\1/g' -e 's/-unsigned$//' | \
	sort -u > ${VERSIONLISTFILE}
chmod a+r ${VERSIONLISTFILE}

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 ${VERSIONLISTFILE} "$@"
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 ${VERSIONLISTFILE} "$@"
fi

rm -f ${VERSIONLISTFILE}

