#!/bin/bash
#
# backup ldap, package selection and debconf values
# run dirvish
#

set -e

DIR="/backup/"
MISC_DIR="${DIR}/tmp/misc/"

# from dirvish:
mount_check() {
    mntout=`tempfile -p mount`
    mount $1 >$mntout 2>&1 || true
    if [ ! -d $1/lost+found ]; then # only works for "real" filesystems :-)
                                        # (Yes, I know about reiserfs.)
        echo "'mount $1' failed?! Stopping."
        echo "mount output:"
        cat $mntout
        rm -f $mntout
        exit 2
    fi

    if stat $1 | grep 'Inode: 2[^0-9]' >/dev/null; then # ditto
        rm -f $mntout
        return 0 # ok
    fi
    echo "$1 isn't inode 2 ?! Mount must have failed; stopping."
    echo ''
    stat $1
    echo "mount output:"
    cat $mntout
    rm -f $mntout
    umount $1
    exit 2
}


if grep -q ${DIR%/} /etc/fstab ; then
    MNT=true
    mount_check $DIR
    trap "rc=$?; umount $DIR; exit $rc" ERR
fi

## Backup LDAP, package selection and debconf data.
## Drop the data in $MISC_DIR and use dirvish for
## the backup, thereby making use of its expire
## mechanism:
if [ -x /usr/sbin/slapcat ] ; then
    slapcat -l $MISC_DIR/LDAP.ldif_new
fi
dpkg --get-selections  > $MISC_DIR/package.selection_new
debconf-get-selections > $MISC_DIR/debconf.selection_new

## Check if the data has changed, if not keep the old file:
for FILE in `ls $MISC_DIR/*_new` ; do
    if diff -qN $FILE ${FILE%_new} >/dev/null ; then
	## nothing changed:
	rm $FILE
    else
	## use new file:
	mv $FILE ${FILE%_new}
    fi
done

chmod 640 $MISC_DIR/*

## dirvish:
if [ ! -x /usr/sbin/dirvish-expire  ]; then exit 0; fi
if [ ! -s /etc/dirvish/master.conf ]; then exit 0; fi

/usr/sbin/dirvish-expire --quiet && /usr/sbin/dirvish-runall --quiet
rc=$?

if [ $MNT ] ; then
    umount $DIR || rc=$?
fi

exit $rc
