#!/bin/sh
# Version 0.9
# Released to the public domain by Daniel M. Webb
THIS=mount-snapshot

function die() {
    echo "$THIS: $*"
    exit 1
}

if [ -z "$1" ]; then
    echo "$THIS - create and mount or unmount a snapshot"
    echo
    echo "usage:"
    echo
    echo "  $THIS mount <snapshot LV name> <snapshot size> <original LV name> <mount point>"
    echo
    echo "  $THIS unmount <snapshot LV name> <mount point>"
    echo
    echo " Example: $THIS /dev/home_vg/backup_lv 1000M /dev/home_vg/home_lv /home_snapshot"
    echo
    echo " NOTE: $THIS expects <mount point> to not exist, and will abort with an"
    echo "       error if it does"
    exit 1
fi
command=$1

if [ $command = mount ]; then
    # Create logical volume backup_lv, which is a snapshot of the normal 
    # home directory logical volume home_lv.
    name=$2
    size=$3
    original=$4
    mount_point=$5
    [ -d $mount_point ] && die "$mount_point already exists, aborting"
    lvcreate --snapshot --permission r --name $name --size $size $original \
        || die "error during lvcreate --snapshot --permission r " \
               "--name $name --size $size $original"
    mkdir $mount_point || die "error during mkdir $mount_point"
    mount $name $mount_point || die "error during mount $name $mount_point"

elif [ $command = unmount ]; then
    name=$2
    mount_point=$3
    sleep 5
    umount $mount_point
    if [ $? -ne 0 ]; then
        echo "processes using $mount_point:"
        fuser -m $mount_point
        echo "All processes:"
        ps -efw
        die "error during umount $mount_point"
    fi
    rmdir $mount_point || die "error during rmdir $mount_point"
    lvremove -f $name || die "error during lvremove -f $snapshot_dev"

else
    die "unknown command: $command"
fi
