#!/bin/sh

set -e

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

