#!/bin/sh

# Usage: clean-schroots

# Remove any LVM snapshots and chroots left behind by schroot.  Not
# normally necessary as schroot should clean up after itself.

: ${VG=/dev/dink}
set -x
for i in $(
    for dir in "$VG" /var/lib/schroot/mount /var/lib/schroot/session; do
        cd "$dir"
        for i in *-*-sbuild-*-*-*-*-*; do
            echo "$i"
        done
    done | \
    sort -u | grep -v "\*"
); do
    schroot -ec "$(echo "$i" | sed 's/-cow$//')"
    if [ "$1" = "-f" ]; then
        tac /proc/mounts | cut -d" " -f2 | fgrep "/var/lib/schroot/mount/$i" | xargs -rn1 umount -l
        lvremove -f "$VG/$i"
        rmdir /var/lib/schroot/mount/"$i" /var/lib/schroot/session/"$i"
	if ! [ -e "$VG/$i" ]; then rm "$VG/$i"; fi
    fi
done
