#! /bin/sh
#
# A script to be called by cron that saves files to a tarfile.
#
# Configure the variables SPEED and DEVICE to meet your CD recorder's
# specifications.
#
# Filipe Bonjour, 18 Jan 2003
# Last modified,  19 Jun 2005
#

#
# Making sure that we don't create the image in the
# directory we are backing up is a good precaution!
#
TMP=/tmp/backup
PWD=`pwd`
let "MAXSIZE = 98070 * 1024"

#
# Executables needed
#
TAR=/bin/tar

#
# Create backup dir
#
if [ ! -d $TMP ]; then
	echo "Creating backup directory \"$TMP\""
	mkdir -p -m 700 $TMP
fi

#
# Get the filename containing the directories to backup, which is ".backup" in a user's
# home directory. The user's login is provided as the first argument of the script
#
if [ $# -lt 1 ]; then
    echo "Usage: backupcd username"
    exit 127
else
    USR=${1}
    HOMEDIR=`cat /etc/passwd | grep "^$USR:" | cut -d":" -f 6`
    TARFILE=${TMP}/backup_${USR}.tar
    UFILE=${HOMEDIR}/.backup

    cd ${HOMEDIR} > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo "Could not find home directory for user ${USR}. Exiting..."
	exit 127
    fi

    if [ ! -f ${UFILE} ]; then
	echo "The file ${UFILE} does not exist. Exiting..."
	exit 127
    fi
fi

#
# Create the tar archive, and add files and directories one at a time
#
if [ -f ${TARFILE} ]; then
    rm ${TARFILE}
fi
echo $PWD > .initdir
${TAR} cf ${TARFILE} .initdir
rm .initdir

browser=0
exec 4<${UFILE}
while read -u4 line; do
    # If backing up a browser, clean up first not to backup the cache!
    if [ "$browser" = "0" ]; then
        if [ "$line" = ".galeon" -o "$line" = ".mozilla" ]; then
            browser=1
            echo "Cleaning browsers' caches to reduce backup size."
            /usr/local/bin/clean_browsers.pl -u $USR
        fi
    fi

    echo "Adding file/directory $line"
    ${TAR} -psrf ${TARFILE} $line
done
exec 4<&-

#
# Compress tar archive
#
if [ -f ${TARFILE}.bz2 ]; then
    rm ${TARFILE}.bz2
fi
echo "Compressing tar archive"
bzip2 ${TARFILE}

chown root.users ${TARFILE}.bz2
chmod 640 ${TARFILE}.bz2

cd ${PWD}

exit 0

#
# EOF
#
