#!/bin/bash

#
# Backup
#

NB_MAX_ARCHIVES=5
create_archive=0
verbose=1

function usage()
{
    echo "Backup utility"
    echo ""
    echo "usage : sar.sh [options]"
    echo ""
    echo "Options :"
    echo "-s|--src"
    echo "\tSource directory"
    echo ""
    echo "-d|--dst"
    echo "\tDestination directory"
    echo ""
    echo "-a|--archive"
    echo "\tCreate an archive of dst"
    echo ""
    echo "-v|--verbose"
    echo ""
    
    exit 0
}

function debug()
{
    [ $verbose -eq 0 ] && return

    echo $1
}

[ $# -eq 0 ] && usage

while getopts "s:d:avh" arg ; do
    case $arg in
	s|src)
	    src=$OPTARG
	    ;;
	d|dst)
	    dst=$OPTARG
	    ;;
	a|archive)
	    create_archive=1
	    ;;
	v|verbose)
	    verbose=1
	    ;;
	h|help)
	    usage
	    ;;
    esac
done

if [ ! -d "$src" ] ; then
    echo "$src is not a directory"
    exit 1
fi

if [ ! -d "$dst" ] ; then
    echo "$dst is not a directory"
    echo -e "Backup not mounted" | mail -s "Error with backup" gregory@soutade.fr
    exit 1
fi

backup_mounted=`ls -l $dst | wc -l`

if [ $backup_mounted -eq 1 ] ; then
    echo -e "Backup not mounted" | mail -s "Error with backup" gregory@soutade.fr
    exit 1
fi

if [ $create_archive -eq 0 ] ; then
    debug "rsync from $src to $dst"
    if [ $verbose -eq 1 ]; then
	ver='-v'
    else
	ver=''
    fi
    rsync -a --exclude '/tmp' --exclude '/media' --exclude '/proc' --exclude '/sys' --exclude '/dev' $ver $src $dst
fi

day=`date "+%d"`

if [ $day -eq 1 ] ; then
    create_archive=1
fi

if [ $create_archive -eq 1 ] ; then
    d=`date "+%Y_%m_%d"`
    a=`basename $dst`
    file="$dst/../"$a"_"
    filename=$file"$d.tar.bz2"
    [ -e "$filename" ] && rm -f $filename
    tar -jcvf $filename $dst > /dev/null 2> /dev/null

    debug "Archive $filename created"
    nb_archives=`ls -l $file*  2>/dev/null | wc -l`
    
    debug "Nb archives $nb_archives"
    while [ $nb_archives -gt $NB_MAX_ARCHIVES ] ; do
	archive=`ls -l $file* | cut -d' ' -f8`
	rm -f $archive
	debug "Delete $archive"
	nb_archives=`ls -l $file*  2>/dev/null | wc -l`
    done
fi

hdparm -Y /dev/disk/by-uuid/590f30b1-7727-4d0a-a86a-2360ec0b3f88
