#!/bin/bash
#
# Create debian files from *.in files
#

set -e

usage()
{
	echo 'Usage : DEB_SUBST_<var1>=<val1> ... DEB_SUBST_<var1>=<val1> fixdeb [-sc|--gen-control] <file1.in> [file1.in] ... [filen.in]'
	echo '  Changes environment variables with their values. The variables to be'
	echo '  changed should be exported prefixed with DEB_SUBST_<name of the variable>'
	echo '        --gen-control: do not skip generating control file, by default it will be ignored'
	echo '        <files.in> = space separated list to debian files templates'
	echo
	echo '  List of defined variables'
	set | grep '^DEB_SUBST_'
	exit 1
}

true  ${DEB_SUBST_PACKAGEVERSION:=$(dpkg-parsechangelog | sed -ne's,^Version: \(.*\),\1,p')}
true  ${DEB_SUBST_VERSION:=$(echo $DEB_SUBST_PACKAGEVERSION | sed -ne's,^\([0-9.]*\).*,\1,p')}
true  ${DEB_SUBST_DEBVERSION:=$(echo $DEB_SUBST_PACKAGEVERSION | awk -F '-' '{ print $NF }')}
true  ${DEB_SUBST_UPSTREAM_VERSION:=$(echo ${DEB_SUBST_PACKAGEVERSION} | cut -f 1 -d -)}
true  ${DEB_SUBST_UPSTREAM_MAIN_VERSION:=$(echo ${DEB_SUBST_UPSTREAM_VERSION} | sed -e 's/^\([0-9\.]*\).*/\1/')}
true  ${DEB_SUBST_PACKAGESUFFIX:=-${DEB_SUBST_UPSTREAM_MAIN_VERSION}}
true  ${DEB_SUBST_PRIORITY:=$(($(echo ${DEB_SUBST_VERSION}.0.0.0.0 | sed -e 's@\([0-9]\)\+\.\([0-9]\)\+\.\([0-9]\+\)\.\([0-9]\+\).*@((\1*100+\2)*100+\3)*100+\4@')))}
true  ${DEB_SUBST_TARGET:=$(dpkg-architecture -qDEB_BUILD_ARCH)-$(dpkg-architecture -qDEB_BUILD_ARCH_OS)}

if test ${1} = '--gen-control'
then
	echo ========== Genrating debian/control as per explicit request ==========
	gen_control=true
	shift
else
	gen_control=false
fi
if test $# -lt 1
then
	usage
fi

echo 'List of defined variables'
set | grep '^DEB_SUBST_'
SUBST_CMD=$(set | sed -n -e 's/^DEB_SUBST_\([A-Z_]\+\)=\(.*\)/-e s@\${\1}@\2@g/p')

for i in $*
do
	f=$(basename ${i} .in)
	if  ${gen_control} || test ${f} != 'control'
	then
		d=$(dirname ${i})
		o=${d}/${f/./${DEB_SUBST_PACKAGESUFFIX}.}
		echo "  * Generating ${o}"
		sed ${SUBST_CMD} ${i} > ${o}
	fi
done
