#!/bin/bash
#
# Author : vincent.benoit@benserv.fr
# Date : Novembre 2022
# Version : 1.0.0
# Brief : création du package Debian ncessaire pour le Frontend du configurateur
#
################################################################################

build_prod() {
	ngpath="$1"
	$ngpath build --configuration "production" --output-path "prod/app-configurateur"
}

create_deb() {
	dirname="configurateurfront-$1"
	/usr/bin/mkdir -p "$2/bdist_deb/$dirname"
	cd "$2/bdist_deb/$dirname"

	debvers=`/usr/bin/cat /etc/debian_version`
	IFS='.'
	read -ra vers <<< "$debvers"
	if [ "$vers" == "10" ]; then
		# Write compat file to deb template for Debian 10.x
		cat > $2/misc/template/compat << EOF
11
EOF
	fi
	/usr/bin/dh_make -t $2/misc/template -n -y -i -d -e "vincent.benoit@benserv.fr" -c mit
	cd "$2"
	if [ -d "$2/prod" ]; then
		ret=$(/usr/bin/cp -a "$2/prod/app-configurateur" "$2/bdist_deb/$dirname")
		echo "$ret"
	fi
#	ngpath="$3"
#	$ngpath build --configuration "production" --output-path "bdist_deb/$dirname/app-configurateur"
	cd "$2/bdist_deb/$dirname"
	/usr/bin/find $2/misc -type f -name "*.conf" -exec /usr/bin/cp -a {} . \;
	/usr/bin/dpkg-buildpackage -b -uc -us -rfakeroot
	/usr/bin/rm -f $2/misc/template/compat
	cd ..
	if [ ! -d "$2/dist" ]; then
		/usr/bin/mkdir -p $2/dist
		/usr/bin/find . -type f -name "*.deb" -exec /usr/bin/cp -a {} $2/dist \;
	fi
}

echo "*** Remove old dirs ***"
/usr/bin/rm -rf bdist_deb dist
echo "*** read version ***"
vers=`/usr/bin/cat VERSION`
echo "VERSION => $vers"
rootpath=`pwd`
ngpath=`whereis ng |awk -F ': ' '{print $2}'`
echo "*** Build prod app ***"
build_prod "$ngpath"
echo "*** Create Debian Misc Package ***"
create_deb "$vers" "$rootpath" "$ngpath"
