#!/bin/sh

set -e

SNAP_ID=$1
SNAP_MOUNTPOINT="$2"
SNAP_ORIG_PATH="$5"

remove_overlay() {
	if test -e "$SNAP_ORIG_PATH/.overlay_$SNAP_ID"
	then
		LODEV=`losetup -j "$SNAP_ORIG_PATH/.overlay_$SNAP_ID" | cut -d':' -f1`
		if [ "x$LODEV" != x ]
		then
			losetup -d $LODEV
		fi
		rm "$SNAP_ORIG_PATH/.overlay_$SNAP_ID"
	fi
}

if ! test -e $SNAP_MOUNTPOINT
then
    echo "Snapshot at $SNAP_MOUNTPOINT was already removed"
    [ ! -e "$SNAP_ORIG_PATH/.datto_$SNAP_ID" ] || rm "$SNAP_ORIG_PATH/.datto_$SNAP_ID"
    [ ! -e "${SNAP_MOUNTPOINT}-num" ] || rm "${SNAP_MOUNTPOINT}-num"
	remove_overlay
    exit 0
fi

if ! df -T -P | egrep " ${SNAP_MOUNTPOINT}\$" > /dev/null 2>&1
then
    echo "Snapshot is not mounted. Already removed"
    rm "${SNAP_MOUNTPOINT}-num"
    rmdir "${SNAP_MOUNTPOINT}"
    [ ! -e "$SNAP_ORIG_PATH/.datto_$SNAP_ID" ] || rm "$SNAP_ORIG_PATH/.datto_$SNAP_ID"
    remove_overlay
    exit 0
fi

NUM=`cat "${SNAP_MOUNTPOINT}-num"` || true

if [ "x$NUM" = "x" ]
then
    echo "Cannot get device number from ${SNAP_MOUNTPOINT}-num"
    exit 1
fi

echo "Unmounting /dev/datto$NUM at /mnt/urbackup_snaps/$SNAP_ID..."

if ! umount /mnt/urbackup_snaps/$SNAP_ID
then
	lsof | grep /mnt/urbackup_snaps/$SNAP_ID || true
    echo "Unmounting /mnt/urbackup_snaps/$SNAP_ID failed. Retrying in 10s..."
    sleep 10
    umount /mnt/urbackup_snaps/$SNAP_ID
fi


rm "${SNAP_MOUNTPOINT}-num"
rmdir "${SNAP_MOUNTPOINT}"

echo "Removing devicemapper snapshot..."

dmsetup remove "wsnap-$SNAP_ID"

remove_overlay

echo "Destroying dattobd snapshot /dev/datto$NUM..."

dbdctl destroy $NUM

[ ! -e "$SNAP_ORIG_PATH/.datto_$SNAP_ID" ] || rm "$SNAP_ORIG_PATH/.datto_$SNAP_ID"

exit 0