#!/bin/bash

dir='/backup'
num='30' #number of backups to keep

home='~/'
system='/etc'


ls $dir | grep "[0-9]" > ~/file_list.tmp # a list of all the folders in the backup folder

yesterday=`cat ~/file_list.tmp | tail -1` # finds the last item in the list of folders, which would be the most recent
today=`date --rfc-3339='date'`  # todays date in a clean format

yesdir=$dir/$yesterday
todir=$dir/$today

# Check if Root
if [ "$(whoami)" != "root" ]; then
    echo "Sorry, you are not root."
    exit 1
fi

echo ""
echo "Today is $today"

# RSYNC home folder
echo -n Backing up home...
mkdir -p $todir/home
rsync -a --exclude="/.gvfs/" --link-dest=$yesdir/home $home/ $todir/home/
echo ..done.

echo -n Updating latest...
rm $dir/latest
ln -s $dir/$today $dir/latest
echo ..done.

# keeps rolling backup
echo Deleting extra...
for i in $(cat ~/file_list.tmp); do
    x='false'
    for j in $(cat ~/file_list.tmp | tail -$num); do
        if [ "$i" == "$j" ]; then
            x='true'
        fi  
#        echo $i =? $j, $x #  for debugging
    done
    if [ "$x" != "true" ]; then
        echo -n deleting $i ...
        rm -r $dir/$i
    fi  
done
echo done.


# closing off
rm ~/file_list.tmp