#!/bin/bash
#
# $Id: simplebackup,v 1.16 2007-05-13 08:05:07 mitch Exp $
#
# Simple backup script by Christian Garbs <mitch@cgarbs.de>
# Licensed under GNU GPL.
#

# initial setup
set -e
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
RCFILE=~/.simplebackup.conf

# help wanted?
if [ "$1" = "-h" ]; then
    echo "usage:"
    echo -e "\t$0 [-h] [configuration_file]"
    exit 0
fi

# other configuration file given?
if [ "$1" ]; then
    RCFILE="$1"
fi

# check permissions on configuration file
if [ $(( 0$(stat -c %a "$RCFILE") & 0022 )) -gt 0 ] ; then
    echo Configuration file is writeable by group or others.
    echo As this file is executed under your userid, this is a
    echo security risk.  A malicious user could add a command to
    echo remove the contents of your home directory, for example.
    echo Change the permissions to something like 600 or 644.
    exit 2
fi

# set default values
extracommands() { :; }
postcopy() { :; }
postbackup() { :; }

# more initialization
source "$RCFILE"
TARGET="$NAME"-$(LANG=C date +%Y%m%d)

# check configuration
if [ -z "$TARGETDIR" ] ; then
    echo TARGETDIR is not set
    exit 3
else
    if [ ! -d "$TARGETDIR" ] ; then
	echo TARGETDIR is no directory
	exit 3
    fi
fi

if [ -z "$WORKDIR" ] ; then
    echo WORKDIR is not set
    exit 4
fi

if [ -z "$BACKUPDIRS" ] ; then
    echo BACKUPDIRS is not set
    exit 5
fi

if [ -z "$NAME" ] ; then
    echo NAME is not set
    exit 6
fi

if [ -z "$LOCKFILE" ] ; then
    echo warning: no LOCKFILE is given, multiple instances may run
fi

if [ -z "$NICELEVEL" ] ; then
    NICELEVEL=0
fi

# init
if [ "$LOCKFILE" ] ; then
    [ -e "$LOCKFILE" ] && echo "another backup is already running" 1>&2 && exit 1
    echo $$ > "$LOCKFILE"
fi
renice $NICELEVEL $$ > /dev/null

# prepare temporary directory
echo "setting up"
rm -rf "$WORKDIR"
mkdir -m 700 -p "$WORKDIR"
chown $UID "$WORKDIR"

# execute extra commands
(
    extracommands
)

# display chroot
if [ "$CHROOT" ]; then
    echo "chroot to $CHROOT"
    if [ ! -d "$CHROOT" ]; then
	echo "chroot path not found!"
	exit 3
    fi
fi

# backup files
OLDIFS="$IFS"
IFS=":"
for DIR in $BACKUPDIRS; do
    if [ -d "$CHROOT$DIR" ]; then
	echo "backing up $DIR"
	mkdir -p "$WORKDIR$DIR"
	(cd "$CHROOT$DIR" ; tar -c .) | (cd "$WORKDIR$DIR" ; tar -x)
    else
	echo "$DIR is no directory!"
    fi
done
IFS="$OLDIFS"

# execute extra commands after copying
(
    postcopy
)

# build big archive
echo "renaming working directory"
cd "$TARGETDIR"
rm -rf "$TARGETDIR/$TARGET"
mv "$WORKDIR" "$TARGET"

echo "building archive"
BACKUPFILE="$TARGET.tar.bz2"
(
    umask 0377
    tar -cjf "$BACKUPFILE" "$TARGET"
)
rm -rf "$TARGET"

# execute postbackup commands
export BACKUPFILE
(
    postbackup
)

echo "finished"
[ "$LOCKFILE" ] && rm "$LOCKFILE"
exit 0
