#!/bin/bash

# @author: <yves.frederix@cs.kuleuven.be>

#set -e # Ik zou dit graag zetten, maar blijkbaar is er geen manier om te
		# voorkomen dat rsync stopt op onleesbare bestanden (zelfs als deze in
		# diep in de directory structuur van een geignorede directory
		# zitten...)

#####################################################

CONFIG=$HOME/.csbackuprc

#####################################################

echo "##################################################"
echo "Starting csbackup.sh -- $(date)"
echo ""

# Parse command line options
TEMP=`getopt -o kseicl:m: --long keys,setup,inside-cs,etc,crontab,logfile:,mailreminder: -n 'csbackup.bash' -- "$@"`

[ "$?" != 0 ] && exit 1

eval set -- "$TEMP"
while true; 
do
	case "$1" in
		-s|--setup) DOSETUP=1; shift ;;
		-k|--keys) DOSETUPKEYS=1; shift ;;
		-i|--inside-cs) ONLYINSIDECS=1; shift ;;
		-e|--etc) DOETC=1; shift ;;
		-c|--crontab) DOCRONTAB=1; shift ;;
		-l|--logfile) LOGFILE="$2"; shift 2 ;;
		-m|--mailreminder) EMAILREMINDER="$2"; shift 2 ;;
		--) shift; break ;;
		*) echo "Internal error!" ; exit 1 ;;
	esac
done

DATE=`date +%Y%m%d`

# Are we running in script mode or with GUI?
SUDO=sudo
[ "$DISPLAY" = "" ] || SUDO=gksudo

#####################################################
# Some helper functions
#####################################################

function notify(){
	MSG="$1"
	ICON="$NOTIFYICON"
	OPTS="-u critical"

	[ "$2" != "" ] && ICON="$2"
	[ "$3" != "" ] && OPTS="$3"

	if [ "$(which notify-send)" != "" ];
	then
		OPTS="$OPTS -t 20000"
		[ "$ICON" != "" ] && OPTS="$OPTS -i $ICON"
		eval "DISPLAY=:0.0 notify-send $OPTS \"CS backup $MSG\" 2>/dev/null"
	fi
}

function fail(){
	ERRORCODE=$?
	if [ "$ERRORCODE" = "12" ];
	then
		# 12 = No such file or directory
		ADDITIONALMSG=" Did you forget to run '$0 --setup'??"
	fi
	echo "Error: $1$ADDITIONALMSG"
	notify "Backup failed. Error was '$1'$ADDITIONALMSG" $FAILNOTIFYICON
	exit 1
}

type -f insidecs > /dev/null 2>&1 || function insidecs(){
	IP=$(/sbin/ifconfig eth0 | sed -n 's/.*inet *addr:\([0-9\.]*\).*/\1/p')
	[ "${IP:0:6}" = "134.58" ] && true && return
#	IP=$(/sbin/ifconfig wlan0 | sed -n 's/.*inet *addr:\([0-9\.]*\).*/\1/p')
#	[ "${IP:0:7}" = "192.168" ] && true && return
	false
}

function create_default_config(){
	cat > $CONFIG << DELIM
# Full hostname of the file server
BACKUPHOST=newton.cs.kuleuven.be

# Username on the file server
BACKUPHOSTUSER=$LOGNAME

# Name of the backup directory on the server. 
# Files will end up in \$BACKUPHOST:/home/\$BACKUPHOSTUSER/\$BACKUPDIR.
BACKUPDIR=${BACKUPDIR:=backup_$(hostname)_$USER} 

# Full path to the ssh key to use. To be able to use a crontab, the passphrase
# for this key should be empty.
KEYFILE=$HOME/.ssh/id_rsa_backup

# File containing the directories/files to backup.
BACKUPLIST=$HOME/.csbackupdirs

# Add extra exclude patterns to exclude from backup. E.g., to exclude all .o
# files you would write:
# EXCLUDEPATTERNS=("*.o")
# Other examples are:
# EXCLUDEPATTERNS=("directory name with spaces" "otherdir_without" "yetanotherdir")
EXCLUDEPATTERNS=(".thumbnails/" "thumbnails/" ".cache/" ".Cache/" "Trash/" "NoCsBack/" "*.swp")

# Include dotfiles and dotdirs in backup from given directories. Format is
# space separated list. E.g., to backup all dotfiles in your home dir, you
# would write:
# DOTFILEDIRS="$HOME"
DOTFILEDIRS=""

# Do we want to backup the files in /etc? Set to "no" if using in a cronjob as
# this requires sudo read access.
BACKUP_ETC="no"
DELIM
}

#####################################################
# Read configuration
#####################################################

if ! [ -f $CONFIG ];
then 
	echo "Warning: $CONFIG not found.. I will create this file using default settings."
	create_default_config
	echo " +-> Done. "
	echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	echo "+  Now you should edit and correct the settings in this file! +"
	echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	exit 0
fi

# Read config
source $CONFIG

# Default config
DOTFILEDIRS=${DOTFILEDIRS:=""}
BACKUPLIST=${BACKUPLIST:=$HOME/.csbackupdirs}
BACKUPHOST=${BACKUPHOST:=newton.cs.kuleuven.be}
BACKUPHOSTUSER=${BACKUPHOSTUSER:=$LOGNAME}
BACKUPDIR=${BACKUPDIR:=backup_$(hostname)} # The backup dir on the server will be $HOME/$BACKUPDIR
BACKUP_ETC=${BACKUP_ETC:="no"}
KEYFILE=${KEYFILE:=""}
NOTIFYICON=${NOTIFYICON:="/usr/share/csbackup/icons/notification-device.svg"}
FAILNOTIFYICON=${FAILNOTIFYICON:="/usr/share/csbackup/icons/notification-device-red.svg"}
OKNOTIFYICON=${OKNOTIFYICON:="/usr/share/csbackup/icons/notification-device-green.svg"}
#EXCLUDEPATTERNS=("*.bla") 


# Extra values
BACKUPTARGET="$BACKUPHOSTUSER@$BACKUPHOST:$BACKUPDIR"
BACKUPTARGETMIRRORDIR="$BACKUPTARGET/mirror" # Do not change 'mirror'
DEFAULTBACKUPLISTDIR="$HOME/csbackup"
EXCLUDE=""

for i in `seq 0 $((${#EXCLUDEPATTERNS[@]}-1))`;
do
	PATTERN="${EXCLUDEPATTERNS[$i]}"
	if [ "$PATTERN" != "" ];
	then
		EXCLUDE[$((2*$i))]="--exclude"
		EXCLUDE[$((2*$i+1))]="$PATTERN"
	fi
done 

if ! [ -f $BACKUPLIST ];
then
	echo "Warning: '$BACKUPLIST' not found. Only doing backup for $DEFAULTBACKUPLISTDIR..."
	echo ""
#	fail " $BACKUPLIST not found... abort."
fi

if [ "$KEYFILE" = "" ];
then
	fail "KEYFILE cannot be empty. Specify a valid value in '$CONFIG'... abort."
fi

if [ ! -e "$KEYFILE" ] || [ "$DOSETUPKEYS" = "1" ];
then
	echo "Warning: SSH key '$KEYFILE' not available."
	if [ ! -e "$KEYFILE" ] && [ -e "$KEYFILE.pub" ];
	then
		echo " +-> Mmm, public key $KEYFILE.pub exists, but private key is unavailable..."
		fail " +-> Generate a valid keypair using the command 'ssh-keygen -N \"\" -t rsa -f $KEYFILE'... abort."
	else
		echo " +-> Generating this keypair."
		ssh-keygen -t rsa -f "$KEYFILE" -N ""
		echo "   +-> OK"
		echo " +-> Now copying the public key to $BACKUPHOST..."
		( ssh-copy-id -i $KEYFILE $BACKUPHOSTUSER@$BACKUPHOST > /dev/null \
			|| ( rm -f $KEYFILE $KEYFILE.pub && fail "Cannot copy $KEYFILE..." ) ) && \
		echo "   +-> OK"
	fi
	exit 1
fi

#####################################################
# React to the command line options
#####################################################

# Do setup of the directory structure on the server 
if [ "$DOSETUP" = "1" ];
then
	echo "Preparing the directory structure on $BACKUPHOST..."
	TMPDIR=/tmp/csback_server_$RANDOM
	mkdir -p $TMPDIR
	(
		cd $TMPDIR
		mkdir -p ./$BACKUPDIR/info
		mkdir -p ./$BACKUPDIR/mirror
		eval "rsync -avz -e \"ssh -i $KEYFILE\" -R . $BACKUPHOSTUSER@$BACKUPHOST:" || fail "Error preparing the server..."
	)
	echo "  +-> OK"
fi

if [ "$DOCRONTAB" = "1" ];
then
	MIN=$(( $RANDOM % 60 ))
	HOUR=$(( 11 + ($RANDOM % 2) ))
	[ "$ONLYINSIDECS" != "" ] && ONLYINSIDECS="--inside-cs"
	[ "$LOGFILE" != "" ] && LOGFILE=">> $LOGFILE 2>&1"
	echo "Creating cron job. Running backup daily at $HOUR""h""$MIN".
	(crontab -l | sed -e 's/^\([^#].*csbackup .*\)/#\1/'; \
		echo "$MIN $HOUR * * * /usr/bin/csbackup $ONLYINSIDECS $LOGFILE # Automatically added by csbackup script on $(date)"; )\
		| crontab 
	echo "Crontab written. You can check the result manually with 'crontab -e'."
	exit 0
fi

# Force backup of /etc
[ "$DOETC" = "1" ] && BACKUP_ETC="yes"

# If backup is only to be performed inside the cs network, check if this is the
# case. If not, just exit.

if [ "$ONLYINSIDECS" = "1" ]; 
then
	insidecs || fail "Skipping backup at $(date) because not inside CS domain."
fi

if [ "$EMAILREMINDER" != "" ];
then
	echo "Setting up email reminder on $BACKUPHOST..."
	TMPDIR=/tmp/csback_$RANDOM
	mkdir -p $TMPDIR/bin
	(
		cd $TMPDIR
		# 168 hours = 7 days
		((cd /usr/share/csbackup; tar cf - csbackup_mailreminder.sh) | SSH_AUTH_SOCK="" ssh $BACKUPHOSTUSER@$BACKUPHOST "mkdir -p \$HOME/bin; cd \$HOME/bin; tar xf -; (crontab -l | sed -e 's|^\([^#].*csbackup_mailreminder.*\)|#\1|'; echo \"00 00 * * * bash \$HOME/bin/csbackup_mailreminder.sh \$HOME/$BACKUPDIR 168 $EMAILREMINDER # Automatically added by csbackup script on $(date)\"; ) | crontab -") || fail "Cannot setup email reminder"
	) && exit 0
	exit 1
fi

#####################################################
# Backup functions
#####################################################

function backupetc(){
	echo " * Creating backup of system files"
	TMPDIR=/tmp/csback_$RANDOM
	mkdir -p $TMPDIR
	(
		cd $TMPDIR
		echo " Collecting information from 'dpkg -l' ... "
		dpkg -l > dpkg_l.$DATE
		echo "  +-> OK"

		echo " Compressing /etc ... "
		$SUDO tar jcf etc.$DATE.tar.bz2 /etc -P || fail "Error compressing /etc"
		echo "  +-> OK"

		echo "  Copying /etc files to $BACKUPHOST ... "
		eval "rsync -e \"ssh -i $KEYFILE\" -a --delete . $BACKUPTARGET/info" || fail "Error copying /etc files"
		echo "  +-> OK"

		sudo rm etc.$DATE.tar.bz2
	)
}

function backupdirs_onebyone(){
	# As in the function backupdirs _all_ directories are passed in a single
	# command, it might not be clear where exactly the rsync command goes
	# wrong. This function synchronizes the directories one by one so that the
	# error message at least indicates which directory is the culprit.
	FILES=( "$@" )
	for i in "${FILES[@]}";
	do
		echo "Processing $i ..."
		rsync -avz -e "ssh -i $KEYFILE" --filter='dir-merge,e .NoCsBack' "${EXCLUDE[@]}" --delete-excluded --delete -R $i $BACKUPTARGETMIRRORDIR || fail "Error transferring $i..."
	done;
}

function backupdirs(){
	FILES2BACKUP=( "$@" ) # Note: this is an array!
	rsync -avz -e "ssh -i $KEYFILE" --filter='dir-merge,e .NoCsBack' "${EXCLUDE[@]}" --delete-excluded --delete -R "${FILES2BACKUP[@]}" $BACKUPTARGETMIRRORDIR || backupdirs_onebyone "${FILES2BACKUP[@]}"
	echo "  +-> OK"
	echo ""
}

function backupdotdir(){
	DOTFILEDIR=$1
	echo " * Processing DOTFILEDIR = $DOTFILEDIR ..."

	# Save original IFS
	OLDIFS=$IFS
	IFS=$'\n' # Ensures that file names with spaces are dealt with correctly

	# The following assigns to FILES2BACKUP the list of dotfile in the form of
	# a bash array. We use arrays, again because file names with spaces are a
	# pain...
	FILES2BACKUP=($(find $DOTFILEDIR -maxdepth 1 -iname '.*')) 
	backupdirs "${FILES2BACKUP[@]}"

	# Put IFS back
	IFS=$OLDIFS
}


notify "Starting backup to '$BACKUPHOST'..."

#####################################################
# Backup /etc if asked for
#####################################################
if [ "$BACKUP_ETC" = "yes" ]; 
then
	backupetc || fail "huh?"
fi

#####################################################
# Process the rest
#####################################################

# First . (dot) directories
for DOTFILEDIR in $DOTFILEDIRS;
do
	[ -e $DOTFILEDIR ] && backupdotdir $DOTFILEDIR \
		|| echo "Warning: $DOTFILEDIR does not exist. Skipping..."
done

# Then the rest
unset FILES2BACKUP
[ -d $DEFAULTBACKUPLISTDIR ] && FILES2BACKUP[0]="$DEFAULTBACKUPLISTDIR"
i=1
[ -e $BACKUPLIST ] && while read FILE2BACKUP;
do
	[ "${FILE2BACKUP:0:1}" = "#" ] && echo "  --> Ignoring $FILE2BACKUP" && continue
	[ "${FILE2BACKUP:${#FILE2BACKUP}-1}" = "/" ] && FILE2BACKUP=${FILE2BACKUP:0:${#FILE2BACKUP}-1}
	[ -e $FILE2BACKUP ] && FILES2BACKUP[$i]="$FILE2BACKUP" \
		|| echo "Warning: $FILE2BACKUP does not exist. Skipping..."
	i=$((i+1))
done < $BACKUPLIST

if [ "${#FILES2BACKUP[@]}" != "0" ];
then
	echo " * Processing $FILES2BACKUP..."
	backupdirs "${FILES2BACKUP[@]}"
fi

#####################################################
# Save timestamp of this (successful) backup
#####################################################

(
	TMPDIR=/tmp/tmp_$RANDOM
	mkdir -p $TMPDIR
	cd $TMPDIR
	date +%s > lastbackup
	eval "rsync -e \"ssh -i $KEYFILE\" -a . $BACKUPTARGET/info" || fail "Error copying timestamp to $BACKUPHOST..." > /dev/null 2>&1
)

#####################################################
# Done!
#####################################################

echo " All done!"

notify "Backup to '$BACKUPHOST' successfully completed..." "$OKNOTIFYICON"
