#!/bin/sh
# Copyright © 2005-2007  Roger Leigh <rleigh@debian.org>
#
# schroot is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# schroot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

set -e

if [ -f "$CHROOT_SCRIPT_CONFIG" ]; then
  . "$CHROOT_SCRIPT_CONFIG"
fi

if [ "$AUTH_VERBOSITY" = "verbose" ]; then
  VERBOSE="-v"
fi

if [ "$CHROOT_TYPE" = "lvm-snapshot" ]; then

    if [ $1 = "setup-start" ]; then

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    lvcreate $VERBOSE $CHROOT_LVM_SNAPSHOT_OPTIONS --snapshot \
		--name "$CHROOT_LVM_SNAPSHOT_NAME" "$CHROOT_DEVICE"
	else
	    lvcreate $VERBOSE $CHROOT_LVM_SNAPSHOT_OPTIONS --snapshot \
		--name "$CHROOT_LVM_SNAPSHOT_NAME" "$CHROOT_DEVICE" > /dev/null
	fi

    elif [ $1 = "setup-stop" ]; then

        # The lock needs to be dropped immediately before destroying
        # the device.  There is a small race here, but the lock can't
        # be dropped once the device has been removed.
	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    echo "Removing device lock for $CHROOT_LVM_SNAPSHOT_DEVICE, owned by pid $PID"
	fi
        "$LIBEXEC_DIR/schroot-releaselock" \
	    --device="$CHROOT_LVM_SNAPSHOT_DEVICE" \
	    --pid=$PID || true

	if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	    lvremove $VERBOSE -f "$CHROOT_LVM_SNAPSHOT_DEVICE" || true
	else
	    lvremove $VERBOSE -f "$CHROOT_LVM_SNAPSHOT_DEVICE" > /dev/null || true
	fi

    fi

fi

