#!/bin/bash -x
set -e

EXEC_DIR="`dirname \"$0\"`"              # relative
EXEC_DIR="`( cd \"$EXEC_DIR\" && pwd )`"  # absolutized and normalized
if [ -z "$EXEC_DIR" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi

log () {
    now=$(date "+%Y-%m-%d %H:%M:%S %Z: ")
    echo -e "${now} postinst $@" >> ${EXEC_DIR}/buildDeb.log
}
#Change this to the name of the Debian package being built
PACKAGES=("check-mk-agent" "check-mk-agent-logwatch" "solr-common7" "solr-tomcat7" "libnoggit-java" "libio-prompt-perl");

#Binary destination within the package. Usually the same as $PACKAGE, but not always
## IMPORTANT: check that the copy destination is correct - some of the 
## debian packages don't use the convention of /usr/share/$PACKAGE

#BUILDVERSION=`date +%Y%W%w%H%M%S`

#BUILDVERSION=`date +%Y%m%d`
#BUILDVERSION="${BUILDVERSION}.100"
#BUILDVERSION=`date +%s`

SOURCEDIR="${EXEC_DIR}/src"
BUILDDIR="${EXEC_DIR}/build"
DPKG_DEB=/usr/bin/dpkg-deb;
APTREPOS=/var/www/ubuntu-extra
APTPKG=$APTREPOS/dists/precise/universe/binary-amd64

if [[ -e ${BUILDDIR} ]]; then
  if ! (rm -rf ${BUILDDIR}); then
	log "Failed to remove ${BUILDDIR}"
	exit 1
  fi
fi

if [[ ! -e ${APTREPOS} ]]; then
	log "${APTREPOS} has not yet been created!"
	exit 1
fi

sudo chown -R jenkins:jenkins $APTREPOS
mkdir -p $APTPKG


mkdir -p $BUILDDIR
#Build the precise Packages.gz doc
for PACKAGE in "${PACKAGES[@]}"; do
	if [ -e ${APTREPOS}/${PACKAGE}_*.deb ]; then
		log "${PACKAGE}*.deb exists. moving on."
		continue 	
	fi

	if [ -e ${EXEC_DIR}/${PACKAGE}*.deb ]; then
		if ! (rm ${EXEC_DIR}/${PACKAGE}*.deb); then
			log "failed to remove ${PACKAGE}*.deb"
		fi
	fi

	#copy over sources for build
	if ! (rsync -av --cvs-exclude  ${SOURCEDIR}/${PACKAGE} ${BUILDDIR}/); then
		log "could not copy ${SOURCEDIR}/* to ${BUILDDIR}/${PACKAGE}"
	fi

	#Update the version info in this package
#	sed -i 's/^Version: [.0-9]*/&R'$BUILDVERSION'/' $BUILDDIR/$PACKAGE/DEBIAN/control

	#build the .deb
	sudo chown -R root:root ${BUILDDIR}/${PACKAGE}
	cd ${BUILDDIR} && $DPKG_DEB -b $PACKAGE ..;
#	if ! (rm ${APTREPOS}/${PACKAGE}*.deb); then
#		log "Failed to remove $APTREPOS/${PACKAGE}*.deb"
#	fi

	cd $EXEC_DIR
#	if ! (cp ${EXEC_DIR}/${PACKAGE}*${BUILDVERSION}*.deb ${APTREPOS}); then
	if ! (cp ${EXEC_DIR}/${PACKAGE}*.deb ${APTREPOS}); then
		log "Failed to copy ${EXEC_DIR}/${PACKAGE}*.deb"
		exit 1
	fi
	sudo chown -R jenkins:jenkins ${BUILDDIR}/${PACKAGE}
done

cd $APTREPOS && dpkg-scanpackages . /dev/null | gzip -9c > $APTPKG/Packages.gz
sudo chown -R root:root ${APTREPOS}

if [[ -e ${BUILDDIR} ]]; then
  if ! (rm -rf ${BUILDDIR}); then
	log "Failed to remove ${BUILDDIR}"
	exit 1
  fi
fi
for debian_pkg in ${EXEC_DIR}/*.deb; do
	if [[ -e ${debian_pkg} ]]; then
		if ! (rm -f ${debian_pkg}); then
			log "Failed to remove ${debian_pkg}"
			exit 1
  		fi
	fi
done