#!/bin/bash

cd $(dirname $0)
fn_dummy=
fn_common=
fn_client=
fn_server=

clean() {
	rm -rf debian
	mkdir -p debian
}

fnames() {
	version="$(sed -n "/^Version:/s/^Version:[[:blank:]]//p" common.DEBIAN/control)"
	arch="$(sed -n "/^Architecture:/s/^Architecture:[[:blank:]]//p" common.DEBIAN/control)"
	pname="$(sed -n "/^Package:/s/^Package:[[:blank:]]//p" common.DEBIAN/control)"
	fn_common=${pname}_${version}_${arch}
	pname="$(sed -n "/^Package:/s/^Package:[[:blank:]]//p" client.DEBIAN/control)"
	fn_client=${pname}_${version}_${arch}
	pname="$(sed -n "/^Package:/s/^Package:[[:blank:]]//p" server.DEBIAN/control)"
	fn_server=${pname}_${version}_${arch}
	pname="$(sed -n "/^Package:/s/^Package:[[:blank:]]//p" dummy.DEBIAN/control)"
	fn_dummy=${pname}_${version}_${arch}
}

changes() {
	rm -rf $1.changes	
	changestool --create $1.changes add $1.deb
	changestool $1.changes setdistribution unstable
}

pack() {
	[[ $FAKEROOT ]] || { FAKEROOT=1 fakeroot -- $0 pack; return; }

	version="$(sed -n "/^Version:/s/^Version:[[:blank:]]//p" common.DEBIAN/control)"
	if [[ ${version%.*} == $(date  +%Y.%m.%d) ]] 
	then	suff=$(printf "%02d" $(($(echo ${version##*.} | bc) + 1)))
	else	suff=00
	fi
	version=$(date +%Y.%m.%d.$suff)
	control=$(<common.DEBIAN/control)
	sed -e "/^Version:/s/^.*$/Version: $version/" <<<$control >common.DEBIAN/control

	# dejsem.common
	clean
	cp -a common.DEBIAN debian/DEBIAN
	mkdir -p debian/etc/default debian/usr/lib/dejsem debian/usr/share/dejsem/ssl
	cp -a ../../python/dejsem.pycharm/*.py	debian/usr/lib/dejsem/	
	cp -a ../../ssl/*.pem	debian/usr/share/dejsem/ssl/
	cp -a ../../ssl/dejCA.crt	debian/usr/share/dejsem/ssl/
	cp -a etc/default/dejsem	debian/etc/default/
	chown -R root.root debian
	dpkg-deb -b debian .
	
	# dejsem.client
	clean
	cp -a client.DEBIAN debian/DEBIAN
	sed -e "s/VERSION/$version/g" client.DEBIAN/control >debian/DEBIAN/control
	mkdir -p debian/usr/bin/
	cp -a ../bin/dejsem debian/usr/bin/				
	cp -a ../bin/d.* debian/usr/bin/				
	chown -R root.root debian
	dpkg-deb -b debian .
	
	# dejsem.server
	clean
	cp -a server.DEBIAN debian/DEBIAN
	sed -e "s/VERSION/$version/g" server.DEBIAN/control >debian/DEBIAN/control
	mkdir -p debian/etc/init.d debian/usr/bin
	cp -a etc/init.d debian/etc/
	cp -a ../bin/dejsemd debian/usr/bin/				
	chown -R root.root debian
	dpkg-deb -b debian .
	
	# dejsem.dummy
	clean
	cp -a dummy.DEBIAN debian/DEBIAN
	sed -e "s/VERSION/$version/g" dummy.DEBIAN/control >debian/DEBIAN/control
	chown -R root.root debian
	dpkg-deb -b debian .
	
	fnames
	changes $fn_common
	changes $fn_client
	changes $fn_server
	changes $fn_dummy
	
	clean
}

upload() {
	fnames
	scp -p $fn_common.{deb,changes} $fn_client.{deb,changes} $fn_server.{deb,changes} $fn_dummy.{deb,changes} root@deb.hh.cz:/w/debian/incoming/
}

case $1 in
	clean ) 	clean ;;
	pack )		pack ;;
	upload )	upload ;;
	* )
		pack
		upload
		;;
esac
