#!/bin/bash
# my backup script in /Users/mkljun/backup.sh

DestinationIP="148.88.226.250"
SourceIP=`ifconfig | sed -n '/en0/,/media/p' | grep -v inet6 | grep inet | awk '{print $2}'`
LOGFILE="/Users/mkljun/backup.log"
SourceDir="/Users/mkljun"
DestinationDir="/Volumes/mkljunHome/BackupMac"
SambaDrive="smb://mkljun@MKLJUNDESKTOP/mkljunHome"

## delete a log file if bigger than 50M                                                                                                     
# check if the file exists otherwise create it                                                                                              
if [ ! -f $LOGFILE ]; then `touch $LOGFILE`; fi
LOGSIZE=`ls -l $LOGFILE | awk '{print $5}'`
echo "Size of $LOGFILE = $LOGSIZE bytes."  >> $LOGFILE 2>&1
if [ $LOGSIZE -gt 50000000 ]; then rm $LOGFILE; fi


echo "************************************************************" >> $LOGFILE 2>&1
date >> $LOGFILE 2>&1
echo "************************************************************" >> $LOGFILE 2>&1
echo "Pinging destination machine $DestinationIP:" >> $LOGFILE 2>&1
# ping destination (backup) ip address; output redirected to a log file
ping -c 1 $DestinationIP >> $LOGFILE 2>&1
# check if ping successful
if [ $? != 0 ]
then
    # if ping command not successful, print notification (echo should be in one line!!)
    echo "-t 'Backup failed' -m 'Your IP is $SourceIP. Backup PC $DestinationIP could not be reached'" | xargs /usr/local/bin/growlnotify
    echo "Pinging failed" >> $LOGFILE 2>&1
else
    # mount samba drive (it should be one line)
    osascript -e "try" -e "mount volume \"$SambaDrive\"" -e "end try" > /dev/null 2<&1
    # check if mount was successful
    if [ $? == 0 ]; then
      # this echo should be in one line with a pipe
      echo "-t 'Backup' -m 'Your IP is $SourceIP. Starting backing up now'" | xargs /usr/local/bin/growlnotify
      echo "Backing up" >> $LOGFILE 2>&1
      rdiff-backup $SourceDir $DestinationDir >> $LOGFILE 2>&1
      # if rdiff-backup 
      if [ $? == 0 ]; then
        echo "-t 'Backup' -m 'Backup completed successfully'" | xargs /usr/local/bin/growlnotify
        echo "Backup completed successfully" >> $LOGFILE 2>&1
      else
        echo "-t 'Backup failed' -m 'Something was wrong'" | xargs /usr/local/bin/growlnotify
        echo "Backup failed" >> $LOGFILE 2>&1
      fi
      # delete all backups older than 2 weeks
      rdiff-backup --remove-older-than 2W $DestinationDir >> $LOGFILE 2>&1
    fi
fi