#!/usr/local/bin/bash
# Simple backupscript using rsync
# Written by: S\xf8ren Klintrup <soren at klintrup.dk>
# Get your copy from http://soren.klintrup.dk/backup/
# version 1.1

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
BACKUPUSER=backup
BASEDIR=/backup/
CONFDIR="/usr/local/etc/backup"
DATE=$(date +%Y-%m-%d)
RSYNC_ARGS="-aHrx --delete --delete-excluded --numeric-ids"
HOSTCONF="${CONFDIR}/hostconf.sh"

if [ ${#} -ge 1 ]
then
 for server in ${*}
 do
  unset link linkdest dir DIR DEFAULT_EXCLUDE EXCLUDE HOSTGROUP
  DEFAULT_EXCLUDE=1
  DIR="/etc /usr/local/etc"
  if [ -r ${HOSTCONF} ]
  then
   . ${HOSTCONF}
   host_conf ${server}
  fi
  if [ "${DEFAULT_EXCLUDE}" = "1" ]
  then
   for file in default ${server} ${HOSTGROUP}
   do
    if [ -r "${CONFDIR}/exclude.${file}" ]
    then
     EXCLUDE="${EXCLUDE} --exclude-from=${CONFDIR}/exclude.${file}"
    fi
   done
  else
   for file in ${server} ${HOSTGROUP}
   do
    if [ -r "${CONFDIR}/exclude.${file}" ]
    then
     EXCLUDE="${EXCLUDE} --exclude-from=${CONFDIR}/exclude.${file}"
    fi
   done
  fi
  for dir in ${DIR}
  do
   unset linkdest
   for link in $(ls -1tr ${BASEDIR}/${server}|grep -v ${DATE}|tail -19)
   do
    if [ -d "${BASEDIR}/${server}/${link}/${dir}" ]
    then
     linkdest="${linkdest} --link-dest=${BASEDIR}/${server}/${link}/${dir}"
    fi
   done
   mkdir -p ${BASEDIR}/${server}/${DATE}/${dir}/
   rsync --rsync-path="nice sudo rsync" ${RSYNC_ARGS} ${linkdest} ${EXCLUDE} ${BACKUPUSER}@${server}:/${dir}/ ${BASEDIR}/${server}/${DATE}/${dir}/
  done
 done
else
 echo "please specify servers to backup on commandline"
 echo "example: ${?} test1.example.org test2.example.com"
 echo "note: for automation you need this users ssh key authorized on the destination system"
fi
