#!/bin/sh

set -eu

ME=$(basename $0)

usage () {
	echo "Usage: $ME [-n|--dry-run]"
	echo "Ends all remaining schroot sessions."
	echo ""
	echo "Options:"
	echo "  -n, --dry-run  Only list the sessions that would be ended,"
	echo "                 and do not end them."
	echo "  -h, --help     Print this help."
}

list_sessions () {
	# schroot --all-sessions --list prints each session name prefixed
	# with "session:", while schroot -e -c expects the bare name.
	schroot --all-sessions --list 2>/dev/null | sed 's/^session://'
}

DRY_RUN=no
case "${1:-}" in
"")
	;;
-n|--dry-run)
	DRY_RUN=yes
	;;
-h|--help)
	usage
	exit 0
	;;
*)
	usage
	exit 2
	;;
esac

if ! command -v schroot >/dev/null 2>&1 ; then
	echo "Could not find the schroot command in your PATH." >&2
	exit 1
fi

SESSIONS=$(list_sessions)

if [ -z "${SESSIONS}" ] ; then
	echo "No schroot session to clean."
	exit 0
fi

FAILED=no
for SESSION in ${SESSIONS} ; do
	if [ "${DRY_RUN}" = "yes" ] ; then
		echo "Would end: ${SESSION}"
	else
		echo "Ending: ${SESSION}"
		if ! schroot -e -c "${SESSION}" ; then
			# This happens when the session is in use, for example
			# by a concurrently running sbuild: leave it alone.
			echo "  WARNING: could not end ${SESSION}" >&2
			FAILED=yes
		fi
	fi
done

if [ "${FAILED}" = "yes" ] ; then
	exit 1
fi

exit 0
