#!/bin/bash

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

PIDFILE=/var/run/` basename $0 `.pid

function ConnectNBD
{
    echo ConnectNBD $1...
    
    case $1 in
        start)
	    nbd-client 127.0.0.1 60023 /dev/nbd0
	    ;;
	stop)
	    nbd-client -d /dev/nbd0
	    ;;
	*)
	    echo usage $0 [start stop]
	    ;;
    esac
    
    result=$?
    echo ...done $?
    return $result
}

geheim="Tt7)tC!mYJ8\`4HU:WhPfue27\aLr\".S-"

function Crypt
{
    echo Crypt $1...
    case $1 in
	start)
	    echo $geheim | cryptsetup create edminiv2 /dev/nbd0
	    ;;
	stop)
	    cryptsetup remove edminiv2 
	    ;;
	status)
	    cryptsetup status edminiv2
	    ;;
	*)
	    echo usage $0 [ start stop status ]
	    ;;
    esac
    
    result=$?
    echo ...done $?
    return $result
}

function Mount
{
    echo Mount $1...
    case $1 in
	start)
	    mount /dev/mapper/edminiv2 /mnt/edminiv2 -o relatime
	    ;;
	stop)
	    umount /dev/mapper/edminiv2 
	    ;;
	status)
	    cat /proc/mounts | grep /dev/mapper
	    ;;
	*)
	    echo usage $0 [ start stop status ]
	    ;;
    esac
    
    result=$?
    echo ...done $?
    return $result
}

BG=0

function Exit
{
    if [ $BG -eq 1 ]; then
	mail -s "edmini backup $1" root </tmp/edmini.rsnapshot.log
	rm /tmp/edmini.rsnapshot.log
	rm $PIDFILE
	exit 0
    fi
    echo $1
    exit 0
}

function Main
{
    case $1 in
	mount)
	    ConnectNBD start

	    if ! [ $? -eq 0 ]; then
		echo exit $?
		Exit "NBD fail"
	    fi
    
	    Crypt start
    
	    if ! [ $? -eq 0 ]; then
		ConnectNBD stop
		Exit "Crypt fail" 
	    fi
    
	    Mount start
    
	    if ! [ $? -eq 0 ]; then
		Crypt stop
		ConnectNBD stop
		Exit "Mount fail" 
	    fi
	    return 0
	    ;;
	umount)
	    Mount stop
	    Crypt stop
	    ConnectNBD stop
	    return 0
	    ;;
	run)
	    {
		BG=1
		exec >/tmp/edmini.rsnapshot.log 2>&1
		echo $$>$PIDFILE
		date
	    
		# echo "Zomaar een melding" | mail -s "edmini backup started" root
		Main mount
		
		cd /mnt/edminiv2
		df .
    
		nice rsnapshot -c ~/edmini/rsnapshot.conf daily
		result=$?
		cat /var/log/edmini.rsnapshot
		rm /var/log/edmini.rsnapshot
    
		df .
		cd /

		Main umount
		
		if ! [ $result -eq 0 ]; then
		    Exit Fail
		fi
    
		Exit Success
	    } &
	    ;;
	status)
	    echo according to $PIDFILE
	    if [ -f $PIDFILE ] && [ -d /proc/` cat $PIDFILE ` ]; then
		echo running
	    else
	        echo not running
	    fi
	    ;;
	check)
	    if [ -f $PIDFILE ] && [ -d /proc/` cat $PIDFILE ` ]; then
		BASENAME=` basename $0 `
		date | mail -s "$BASENAME is still running" root
	    fi
	    ;;
    esac
}

Main $1
