#!/bin/bash

INSTALL_BUILD_DEPS=0
SID=0

function usage() {
        [ -n "$@" ] && echo -e "$@\n" > /dev/stderr
        echo "Usage: $0 [--install-build-deps] [--sid]"
        [ -n "$@" ] && exit 1
}

idx=1
while [ $idx -le $# ]
do
        OPT=${!idx}
        case $OPT in
                --install-build-deps)
                        INSTALL_BUILD_DEPS=1
                        ;;
                --sid)
                        SID=1
                        ;;
		-x)
			set -x
			;;
                *)
                        usage "Unkown parameter '$OPT'"
        esac
        let idx=idx+1
done

# Enter source directory
cd $( dirname $0 )

# Install build dependencies
if [ $INSTALL_BUILD_DEPS -eq 1 ]
then
	apt-get update
	apt-get install --no-install-recommends --yes devscripts equivs sed rsync git lsb-release wget ca-certificates
	mk-build-deps --install --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' debian/control
fi

DEBIAN_RELEASE=$( lsb_release -r -s|sed 's/\..*$//' )

# Install build dependencies based on Debian release
if [ $INSTALL_BUILD_DEPS -eq 1 ]
then
	# On Debian Stretch, install GitPython using pip because strect version of python3-git have bugs
	if [ $DEBIAN_RELEASE -eq 9 ]
	then
		apt-get install --no-install-recommends --yes python3-pip
		python3 -m pip install GitPython
	else
		apt-get install --no-install-recommends --yes python3-git
	fi
fi

# Install GPG key (if provided)
if [ -n "$GPG_KEY" ]
then
	[ $INSTALL_BUILD_DEPS -eq 1 ] && apt-get install --no-install-recommends --yes gnupg2
	echo "$GPG_KEY"|base64 -d|gpg --import
fi

# Retreive source package name
SOURCE_PACKAGE_NAME=$( grep -E ^Source: debian/control|sed 's/^Source: //' )

[ $SID -eq 1 ] && DEBIAN_CODENAME=sid || DEBIAN_CODENAME=$( lsb_release -c -s )

# Clean previous build
rm -fr $SOURCE_PACKAGE_NAME-build-deps* dist

# Compute version using git describe
VERSION="$( git describe --tags 2> /dev/null )"

# If no tag exist, git describe will fail: in this case, compute a 0.0 version with same format
# as git describe
[ $? -ne 0 ] && VERSION="0.0-$( git log --oneline|wc -l )-$( git describe --tags --always )"

# Create dist directory
mkdir dist
DIST_DIR=dist/$SOURCE_PACKAGE_NAME-$VERSION
rsync -av --exclude 'dist' --exclude '.git*' --exclude 'build.sh' --exclude 'docker-builds.sh' ./ $DIST_DIR/

# Check gitdch is installed
GITDCH=$(which gitdch)
set -e
if [ -z "$GITDCH" ]
then
        TMP_GITDCH=$(mktemp -d)
        echo "Temporary install gitdch in $TMP_GITDCH"
	wget -O $TMP_GITDCH/gitdch https://gitea.zionetrix.net/bn8/gitdch/raw/master/gitdch
	chmod +x $TMP_GITDCH/gitdch
        GITDCH=$TMP_GITDCH/gitdch
else
        TMP_GITDCH=""
fi

# Compute gitdch extra args
GITDCH_EXTRA_ARGS=()
[ -n "$DEBFULLNAME" ] && GITDCH_EXTRA_ARGS+=( "--maintainer-name" "$DEBFULLNAME" )
[ -n "$DEBEMAIL" ] && GITDCH_EXTRA_ARGS+=( "--maintainer-email" "$DEBEMAIL" )

if [ -e debian/changelog ]
then
	LAST_MANUAL_COMMIT_ID=$( git log --oneline -n1 -- debian/changelog|awk '{print $1}' )
	GITDCH_EXTRA_ARGS+=( "--append" "--revision" "${LAST_MANUAL_COMMIT_ID}..HEAD" )
fi

# Generate debian changelog using generate_debian_changelog.py
$GITDCH \
	--package-name $SOURCE_PACKAGE_NAME \
	--version="${VERSION}" \
	--code-name $DEBIAN_CODENAME \
	--output $DIST_DIR/debian/changelog \
	--release-notes ../release-notes.md \
	--exclude "^CI: " \
	--exclude "^debian: " \
	--exclude "\.gitlab-ci\.yml" \
	--exclude "build\.sh" \
	--exclude "README\.md" \
	--exclude "^Merge branch " \
	--verbose "${GITDCH_EXTRA_ARGS[@]}"

# Clean temporary gitdch installation
[ -n "$TMP_GITDCH" ] && rm -fr $TMP_GITDCH

# Build debian package
BUILD_ARGS=""
[ -z "$GPG_KEY" ] && BUILD_ARGS="--no-sign" || echo "GPG key provide, enable package signing."
cd $DIST_DIR/
dpkg-buildpackage $BUILD_ARGS
