#!/bin/bash

#author dal
#mail dal_ml@me.com
#version 0.1 -> FIRST SHOT/QUICK HACK!
#for now only works on mac

#this script mounts a owncloud-drive depending on the current
#network-situation.
#once mounted two rsyncs are performed.

##########here we go.

SAMBA_HOST=192.168.0.106					#local domain name or ip
SAMBA_PATH=//xyz@192.168.0.106/xyz			#the smb for mounting.

WEBDAV_HOST=my.tld
WEBDAV_PATH=https://my.tld/cloud/files/webdav.php

MOUNTPOINT=/Volumes/owncloud/
OWNCLOUDHOME=~/owncloud/

# The apn of the mobile-net-provider. This should only be reachable
# from within the mobile network itself. In this case sync will
# be aborted, because of possible fees.
#for germany see http://www.nethosting24.de/faq/questions/139/APN-Einstellungen-f%FCr-deutsche-Provider-%3F
MOBILE_APN=internet.eplus.de

if ping -c 1 $MOBILE_APN ; 
then
	echo "aborting you're on a mobile net"
	exit 0
fi

# try to mount remote files regarding to network-situation.
if ping -c 1 $SAMBA_HOST ; 
then
	mkdir $MOUNTPOINT
	mount -t smbfs $SAMBA_PATH $MOUNTPOINT
else
	if ping -c 1 $WEBDAV_HOST ;
	then
		mkdir $MOUNTPOINT
		mount_webdav -i $WEBDAV_PATH $MOUNTPOINT
	else
		echo "not reachable"
		exit 0
	fi
fi


# r = recursive
# v = verbose
# c = check based on checksum         
# a = archive
# u = skip files that are newer on the receiver
# l = copy symlinks as symlinks
# m = prune-empty-dirs
# z = compress files during transfer

#TODO params not elaborated, yet. any rsync-experts out there?
PARAMS=-rvum
#TODO seems not to work propper.
#TODO read excludes from file?
EXCLUDETHIS="--exclude '*.bak' --exclude '*.~' --exclude '.DS_Store' --exclude '.TemporaryItems' --exclude '._.DS_Store' --exclude '._.TemporaryItems'"


#determine the syncing order (which directory is newer?)
#TODO is it possible that the creation of the mountpoint affects the timestamp?
#last few syncs echoed "remote files newer".
if [ $OWNCLOUDHOME -nt $MOUNTPOINT ] ;
then
		echo "local files newer"
		#TODO can rsync syn bidirectional in one command?
		cmd="rsync $PARAMS $EXCLUDETHIS $OWNCLOUDHOME $MOUNTPOINT"
		eval $cmd
		cmd="rsync $PARAMS $EXCLUDETHIS $MOUNTPOINT $OWNCLOUDHOME"
		eval $cmd
elif [ $OWNCLOUDHOME -ot $MOUNTPOINT ];
then
		echo "remote files newer"
		cmd="rsync $PARAMS $EXCLUDETHIS $MOUNTPOINT $OWNCLOUDHOME"
		eval $cmd
		cmd="rsync $PARAMS $EXCLUDETHIS $OWNCLOUDHOME $MOUNTPOINT"
		eval $cmd
else
	exit 0
fi

#will this script unmount the volume?
#if yes, a volumename like ~/.owncloudtmp would be handy.
#


