#!/bin/sh

# Begin variable declaration
self=mjt@nysv.org
emergaddr=mjt@nysv.org
cursize=$(du -sb ~/mail | cut -f1 -d\/ | tr -d [:blank:] )
yestdir="$(echo -n ~/.mail-backup/$(echo -n $(date +"%Y-%m")-$[ $(date +"%d") - 1 ] ) )"

if [ -d "$yestdir-CHECK" ]; then
	oldsize=$(du -sb $yestdir-CHECK | cut -f1 -d\/ | tr -d [:blank:] )
	olddir=$(echo -n $yestdir-CHECK)

elif [ ! -d "$yestdir" ]; then
	oldsize=0
	olddir=none

else
	oldsize=$(du -sb $yestdir | cut -f1 -d\/ | tr -d [:blank:] )
	olddir="$yestdir"
fi

destdir=~/.mail-backup/$(date +"%Y-%m-%d")

# End of variable declaration

echo "Mail Backup Script by mjt (http://nysv.org/~mjt) 0.2"
echo "Distributed under the GPL, used at your own risk."
echo 

if [ ! -d ~/.mail-backup ]; then
	echo "Assuming first run of Mail Backup" | mail -s "[mail-backup] Mail Backup Notice" $self
	echo "Assuming first run of Mail Backup"
	mkdir -p ~/.mail-backup/control
	echo -n "Do you want reports of taken backups? [y/n] "; read rep
	case $rep in
		y|Y|yes|Yes)
			touch ~/.mail-backup/control/rep
			;;
		*)
			echo "ok."
			;;
	esac
fi

if [ ! -d $destdir ]; then
	mkdir $destdir
fi
	
if [ $cursize -lt $oldsize ]; then
	echo -e "Mail compromised at $(date +"%Y-%m-%d %T")\ncurrect size: $cursize bytes\nold size: $oldsize bytes\n\nold dir: $olddir \n\nTaking backup nonetheless to $destdir-CHECK" | mail -s "[mail-backup] Mail Problem on $(hostname) for $(whoami)" $emergaddr
	cp -a ~/mail $destdir-CHECK
elif [ -f ~/.mail-backup/control/rep ]; then
	echo -e "Taking backup at $(date +"%Y-%m-%d %T")\ncurrect size: $cursize bytes\nold size: $oldsize bytes\nold dir: $olddir \n" | mail -s "[mail-backup] Mail Backup taken on $(hostname) for $(whoami)" $self
	cp -a ~/mail $destdir
else
	cp -a ~/mail $destdir
fi

