#!/bin/sh

#####################################################################
# (c) The Institute for Open Systems Technologies Pty Ltd, 2014
# This script is designed to be a pre-exec for a Data Protector filesystem
# object.
# Instead of backing up (say) /var, modify the backup specification to 
# backup /mnt/backup/var and set this script as the pre-exec.
# (And to tidy up afterwards, use its post-exec partner)j


# These two parameters are defaults. You can use the environment variables
# for a backup session to change them.
SNAPSHOT_PREFIX=${SNAPSHOT_PREFIX:-/mnt/backup}
SNAPSHOT_SIZE=${SNAPSHOT_SIZE:-10m}

################################################################

# The parent process' command-line shows which filesystem we are backing up.
# It will look like   hostname:/file/system/path
# We need to find the right line of PS output, get rid of everything up to
# the :/ and get rid of anything afterwards.
ps -fp $PPID
REQUESTED_TO_BACKUP=$(ps -fp $PPID | grep vbda | sed -e 's/.*-volume //' -e 's/ .*//')
LIVE_SOURCE=${REQUESTED_TO_BACKUP#$SNAPSHOT_PREFIX}

echo Taking a snapshot of $LIVE_SOURCE and mounting it to $REQUESTED_TO_BACKUP

SOURCE_DEVICE=$(mount | grep "on $LIVE_SOURCE type" | awk '{print $1}')
echo $SOURCE_DEVICE is mounted on $LIVE_SOURCE 

CLASSIC_DEVICE=$(find /dev/vg* -lname $SOURCE_DEVICE)
echo $CLASSIC_DEVICE is a symlink to $SOURCE_DEVICE

VOLUME_GROUP=$(dirname $CLASSIC_DEVICE)
echo I will make a snapshot using volume group $VOLUME_GROUP

SNAPSHOT_NAME=$(echo $LIVE_SOURCE | tr / _ | tr -dc '[0-9a-zA-Z_]')

# Make sure everything is written to disk
sync
lvcreate --size $SNAPSHOT_SIZE --snapshot --name snap_of$SNAPSHOT_NAME $CLASSIC_DEVICE
mkdir -p $REQUESTED_TO_BACKUP
fsck -y $VOLUME_GROUP/snap_of$SNAPSHOT_NAME
mount $VOLUME_GROUP/snap_of$SNAPSHOT_NAME $REQUESTED_TO_BACKUP
