#!/bin/bash

DEBUG=0
INSTALL_DEPS=0
QUIET_ARG=""

function usage() {
        [ -n "$@" ] && echo -e "$@\n" > /dev/stderr
        echo "Usage: $0 [-x] [-I]"
        echo "  -I/--install-deps   Install build dependencies"
        echo "  -q/--quiet          Enable quiet mode"
        echo "  -x/--debug          Enable debug mode"
        [ -n "$@" ] && exit 1
}

idx=1
while [ $idx -le $# ]
do
        OPT=${!idx}
        case $OPT in
                -I|--install-deps)
                        INSTALL_DEPS=1
                        ;;
		-q|--quiet)
			QUIET_ARG="--quiet"
			;;
                -x|--debug)
                        set -x
                        DEBUG=1
                        ;;
                *)
                        usage "Unkown parameter '$OPT'"
        esac
        let idx=idx+1
done

# Enter source directory
cd $( dirname $0 )

# Install build dependencies
if [ $INSTALL_DEPS -eq 1 ]
then
	echo "Install build dependencies..."
        apt-get update
        apt-get install --no-install-recommends --yes \
		$(grep Build-Depends debian/control|sed 's/Build-Depends: //'|sed 's/([^)]\+)//'|tr -d ',')
fi

echo "Clean previous build..."
rm -fr dist

echo "Detect version using git describe..."
VERSION="$( git describe --tags|sed 's/^[^0-9]*//' )"

echo "Create building environment..."
BDIR=dist/forgejo-$VERSION
mkdir -p $BDIR
[ -z "$QUIET_ARG" ] && RSYNC_ARG="-v" || RSYNC_ARG=""
rsync -a $RSYNC_ARG debian/ $BDIR/debian/

echo "Download forgejo binary..."
[ -n "$QUIET_ARG" ] && CURL_ARG="--silent" || CURL_ARG=""
curl $CURL_ARG --location -o $BDIR/forgejo \
	https://codeberg.org/forgejo/forgejo/releases/download/v$VERSION/forgejo-$VERSION-linux-amd64

echo "Download forgejo configuration example file..."
curl $CURL_ARG --location -o $BDIR/app.ini \
	https://codeberg.org/forgejo/forgejo/raw/tag/v$VERSION/custom/conf/app.example.ini

echo "Adjust forgejo configuration file..."
sed -i 's#^[; ]*APP_NAME *=.*#APP_NAME = Forgejo: Beyond coding. We forge.#' $BDIR/app.ini
sed -i 's#^[; ]*RUN_USER *=.*#RUN_USER = git#' $BDIR/app.ini
sed -i 's#^[; ]*RUN_MODE *=.*#RUN_MODE = prod#' $BDIR/app.ini
sed -i 's#^[; ]*WORK_PATH *=.*#WORK_PATH = /var/lib/forgejo/#' $BDIR/app.ini
sed -i 's#^[; ]*MODE *= *\(console|file|conn\).*#MODE = console#' $BDIR/app.ini
sed -i 's#^[; ]*SECRET_KEY *=.*#;; SECRET_KEY = #' $BDIR/app.ini
sed -i 's#^[; ]*SECRET_KEY_URI *=.*#SECRET_KEY_URI = file:/var/lib/forgejo/secret#' $BDIR/app.ini
sed -i 's#^[; ]*INTERNAL_TOKEN *=.*#;; INTERNAL_TOKEN = #' $BDIR/app.ini
sed -i 's#^[; ]*INTERNAL_TOKEN_URI *=.*#INTERNAL_TOKEN_URI = file:/var/lib/forgejo/internal_token#' $BDIR/app.ini

if [ -z "$DEBIAN_CODENAME" ]
then
	echo "Retreive debian codename using lsb_release..."
	DEBIAN_CODENAME=$( lsb_release -c -s )
else
	echo "Use debian codename from environment ($DEBIAN_CODENAME)"
fi

echo "Generate debian changelog using gitdch..."
GITDCH_ARGS=('--verbose')
[ -n "$QUIET_ARG" ] && GITDCH_ARGS=('--warning')
if [ -n "$MAINTAINER_NAME" ]
then
	echo "Use maintainer name from environment ($MAINTAINER_NAME)"
	GITDCH_ARGS+=("--maintainer-name" "${MAINTAINER_NAME}")
fi
if [ -n "$MAINTAINER_EMAIL" ]
then
	echo "Use maintainer email from environment ($MAINTAINER_EMAIL)"
	GITDCH_ARGS+=("--maintainer-email" "$MAINTAINER_EMAIL")
fi
gitdch \
	--package-name forgejo \
	--version "${VERSION}" \
	--code-name $DEBIAN_CODENAME \
	--output $BDIR/debian/changelog \
	--release-notes dist/release_notes.md \
	"${GITDCH_ARGS[@]}"

BUILD_ARGS=""
if [ -n "$MAINTAINER_NAME" -a -n "$MAINTAINER_EMAIL" ]
then
	echo "Set Maintainer field in debian control file ($MAINTAINER_NAME <$MAINTAINER_EMAIL>)..."
	sed -i "s/^Maintainer: .*$/Maintainer: $MAINTAINER_NAME <$MAINTAINER_EMAIL>/" $BDIR/debian/control
else
	echo "Maintainer email not found in environment, disable signing."
	BUILD_ARGS="--no-sign"
fi

echo "Build debian package..."
cd $BDIR
dpkg-buildpackage $BUILD_ARGS