#! /bin/sh

# Generate a snapshot from svn. This script tries to check-out a new
# copy from svn, and then run "autoreconf" and "make distcheck".

PATH=/opt/subversion/bin:/opt/local/bin:$PATH
export PATH

MYTMPDIR="${TMPDIR:-/Volumes/DataHD/Shared/software/ALBERTA/snapshots}/alberta.$$"
SVNREPOS=https://imperium.math.uni-duisburg.de/alberta/subversion
ALBERTADIST=trunk/albertadist
DATE=$(date -u '+%Y%m%d')
SNAPSHOTDIR=/Volumes/DataHD/Shared/software/ALBERTA/snapshots
NSNAPSHOTS=10 # keep only the most recent 10 snapshots

test -d ${TMPDIR} || mkdir -p ${TMPDIR}

# Pray that we have a running ssh-agent (and only one ...)
#: ${SSH_AGENT_PID=`ps -u claus  |grep ssh-agent|awk '{ print $1; }'`}
#: ${SSH_AUTH_SOCK=`find /tmp -user claus -name "agent.[0-9]*"`}
#export SSH_AGENT_PID SSH_AUTH_SOCK

#if test -z "${SSH_AGENT_PID}" -o -z "${SSH_AUTH_SOCK}"; then
#    echo "No running ssh-agent found" 1>&2
#    exit 1
#fi

trap "chmod -R u+rwX ${MYTMPDIR} ; rm -rf ${MYTMPDIR}" 0

mkdir -p "${MYTMPDIR}"
cd "${MYTMPDIR}"
svn co ${SVNREPOS}/${ALBERTADIST} albertadist
cd albertadist
# own revision
HEADREV=`svn info|awk '/Revision:/ { print $2; }'`
LASTREV=`{ ls -C1 ${SNAPSHOTDIR}/*.gz || true; }|tail -n 1|cut -d '-' -f 3|cut -d '.' -f 1`
if test -n "${LASTREV}"; then
    # figure out if anything has changed.
    for i in . alberta alberta_util demo add_ons doc; do
	(
	    cd $i
	    svn diff -r ${LASTREV} > ${MYTMPDIR}/svn.diff
	)
	if test -s ${MYTMPDIR}/svn.diff; then
	    CHANGED=true
	fi
	if test "z${CHANGED}" = ztrue; then
	    break;
	fi
    done
    if ! test "z${CHANGED}" = ztrue; then
	# nothing changed, do not prepare a new snapshot
	exit 0
    fi
fi
#
# attach the time-stamp to the package
#
VERSTAMP="${DATE}-${HEADREV}"
sed -i "" -e 's/AC_INIT(\[alberta\], [^,]*,/AC_INIT([alberta], ['"${VERSTAMP}"'],/g' configure.ac
./fromsvnreconf.sh
./configure --enable-maintainer-mode || exit 1
make || exit 1
make distcheck || exit 1

if test -f "alberta-${VERSTAMP}.tar.bz2" -a \
        -f "alberta-${VERSTAMP}.tar.gz"; then
    mkdir -p ${SNAPSHOTDIR} || true
    cp alberta-${VERSTAMP}.tar.bz2 alberta-${VERSTAMP}.tar.gz ${SNAPSHOTDIR}
    rm -f `ls -C1 ${SNAPSHOTDIR}/*.tar.gz|head -n -${NSNAPSHOTS}`
    rm -f `ls -C1 ${SNAPSHOTDIR}/*.tar.bz2|head -n -${NSNAPSHOTS}`
    chmod -R a+rX ${SNAPSHOTDIR}
fi
