#!/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
PACKAGE="dataone-cn-dev-scripts";

#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}.106"

SOURCEDIR="${EXEC_DIR}"
BUILDDIR="${EXEC_DIR}/build"
DPKG_DEB=/usr/bin/dpkg-deb;
APTREPOS=/var/www/ubuntu-rpw

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/waltz/share/apache-maven-2.2.1/bin"

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

RESULTS=(`find $EXEC_DIR -name "$PACKAGE*.deb" -print`)

if [[ ${#RESULTS[@]} > 0 ]]; then
       sudo chown jenkins:jenkins $APTREPOS/$PACKAGE*.deb
       find $EXEC_DIR -name "$PACKAGE*.deb" -exec rm -rf {} \;
fi

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

if ! (rsync -av --cvs-exclude ${SOURCEDIR}/usr ${BUILDDIR}/${PACKAGE}); then
  log "could not copy ${SOURCEDIR}/usr 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
cd $BUILDDIR && $DPKG_DEB -b $PACKAGE ..;

RESULTS=(`find $APTREPOS -name "$PACKAGE*.deb" -print`)
if [[ ${#RESULTS[@]} > 0 ]]; then
  find $APTREPOS -name "$PACKAGE*.deb" -exec rm -rf {} \;
fi

cd ..
if ! (cp ${EXEC_DIR}/${PACKAGE}*${BUILDVERSION}*.deb ${APTREPOS}); then
  log "Failed to copy ${EXEC_DIR}/${PACKAGE}*$BUILDVERSION*.deb"
  exit 1
fi

#Build the precise Packages.gz doc
APTPKG=$APTREPOS/dists/precise/universe/binary-amd64;
mkdir -p $APTPKG;
cd $APTREPOS && dpkg-scanpackages . /dev/null | gzip -9c > $APTPKG/Packages.gz;