#!/bin/bash -e

# override nerve-gpb's /usr/local/bin/gbp.sh to be able to run
# and extended postexport script to generate debian/control et al.

# Randomize HOME so it will show up if the HOME directory ends up in the package.
HOME=`mktemp -d`
export HOME
GNUPGHOME=`mktemp -d`
export GNUPGHOME

VERSIONLISTFILE=$1
shift

DIST=${DIST:-`cat /etc/nerve_release`}
ARCH=${ARCH:-amd64}
if [[ -n ${BRANCH_NAME} ]]; then
    echo '##################################################'
    echo '# WARNING: BRANCH_NAME is deprecated!            #'
    echo '# Use "docker run -e DEBIAN_BRANCH=..." instead! #'
    echo '##################################################'

    DEBIAN_BRANCH=$BRANCH_NAME
else
    DEBIAN_BRANCH=${DEBIAN_BRANCH:-`git rev-parse --abbrev-ref HEAD`}
fi

if which npm > /dev/null; then
    npm config set cache /tmp/.npm 2> /dev/null
fi

UPSTREAM_BRANCH=${UPSTREAM_BRANCH:-${DEBIAN_BRANCH}}

# NOTES:
# * set --git-ignore-branch because Jenkins will checkout the code in a
#   "detached HEAD" state by default.
GBP_ARGS="--git-ignore-branch \
--git-debian-branch=$DEBIAN_BRANCH \
--git-upstream-branch=$UPSTREAM_BRANCH"

if [[ -z "${EXPORT_DIR}" ]]; then
    GBP_ARGS="${GBP_ARGS} --git-export-dir=`pwd`/build/${DIST}-${ARCH}"
else
    GBP_ARGS="${GBP_ARGS} --git-export-dir=${EXPORT_DIR}"
fi

# These parameters are passed to dpkg-buildpackage
GBP_ARGS="${GBP_ARGS} -F -nc -sa"

# Import GPG key
if [ -e /tmp/gpg.key ]; then
    # get the fingerprint of the key used
    KEYID=$(gpg --import --with-colons --import-options show-only /tmp/gpg.key | sed '1,/^uid/!d' | grep ^fpr | awk -F ':' '{ print $10; }')

    # import key
    gpg --import /tmp/gpg.key

    echo DEBSIGN_KEYID="${KEYID}" > ~/.devscripts

    # update config for git-buildpackage
    GBP_CONFIG=~/.gbp.conf
    if [[ -e $GBP_CONFIG ]]; then
        sed -i "s/keyid\s*=\s*.*/keyid = ${KEYID}/" $GBP_CONFIG
    else
        echo -e "[DEFAULT]\nkeyid = ${KEYID}" > $GBP_CONFIG
    fi
else
    echo "WARNING: No gpg key found at /tmp/gpg.key. Package will not be signed."
    GBP_ARGS="${GBP_ARGS} --no-sign"
fi

TIMESTAMP=${TIMESTAMP:-`date +%Y%m%d%H%M%S`}
export TIMESTAMP

# use /tmp/genhelper/kvariants as interface to postexport hook
mkdir -p /tmp/genhelper
cp ${VERSIONLISTFILE} /tmp/genhelper/kvariants

# Jenkins will set EXPORT to null
if [[ -n "${EXPORT}" && ${EXPORT} != "null" ]]; then
    GBP_ARGS="--git-export=${EXPORT} ${GBP_ARGS}"
fi

# postexport is set in gbp.conf, so do not override it here
set -x
gbp buildpackage ${GBP_ARGS} "$@"
