#! /bin/bash

# Put exclude patterns into ~/.backup.exclude

# Setup

DEST="/path/to/your/backup/disk/"
SRC="/home/flo/"


#############################################################################
#
# Copyright (c) 2009-2014, Florian Jung
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#
#############################################################################


LC_COLLATE="C" # this script relies on the correct sorting order for [0-9]!

#remove trailing slashes
DEST=$(echo "$DEST" | sed -e 's|\(.*\)/$|\1|')
SRC=$(echo "$SRC" | sed -e 's|\(.*\)/$|\1|')

cd "$DEST"
# get last and current backup names
LAST="$(echo [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | sed -e 's|.* \([0-9]*\)$|\1|')"
NOW=$(date +%Y%m%d)

if echo $LAST | grep '\['; then
  echo "no previous backup found. creating initial backup..."
  LINKDEST=""
else
  echo "last backup was: $LAST"
  LINKDEST="--link-dest=../$LAST/"
fi

echo "today's backup is: $NOW"

if [ $LAST = $NOW ]; then
  echo "ERROR: you already did a backup today"
else
  FOO='';
  if [ x$1 != x ]; then FOO='-n'; fi
# do the backup
  echo rsync -a -v -x $FOO --hard-links "$LINKDEST" --exclude-from="$SRC/.backup.exclude" "$SRC/" "$DEST/$NOW/"
  rsync -a -v -x $FOO --hard-links "$LINKDEST" --exclude-from="$SRC/.backup.exclude" "$SRC/" "$DEST/$NOW/"
  echo
# Disable the next 4 lines at your option
  echo -n "Today's backup took "
  du -sh "$LAST" "$NOW" | tail -n 1 | sed -e "s,$NOW,,"
  echo -n "Total disk usage by backups: "
  du -sh . | sed -e 's,\([kMGT]\).*,\1,'
  echo done!
  echo
fi
