+CHROOT="$1"; shift
+APTCMD="$1"; shift
+PACKAGES="$*"
+
+declare -a suffix
+suffix[0]=""
+
+if [ -x /usr/bin/dchroot ] ; then
+ chroots=$(dchroot -l 2>&1 | awk -F": " '{print $2}' | tr ' ' '\n')
+ method=dchroot
+ suffix[${#suffix[*]}]="_$(dpkg --print-architecture)"
+ allowed_filter='.'
+elif [ -x /usr/bin/schroot ] ; then
+ chroots=$(schroot -l | awk -F":" '{print $2}' | grep -- '-dchroot$' )
+ method=schroot
+ suffix[${#suffix[*]}]=""
+ suffix[${#suffix[*]}]="-dchroot"
+ suffix[${#suffix[*]}]="-$(dpkg --print-architecture)-dchroot"
+ allowed_filter='-dchroot$'
+else
+ echo >&2 "Cannot find chroot wrapper."
+ exit 1
+fi
+
+requested_chroot=""
+while read c; do
+ for (( i = 0 ; i < ${#suffix[*]} ; i++ )); do
+ if [ "$c" == "$CHROOT${suffix[$i]}" ]; then
+ requested_chroot="$c"
+ fi
+ done
+done <<< "$chroots"
+
+if ! [ -n "$requested_chroot" ]; then
+ echo >&2 "$CHROOT is not a valid dchroot. Available chroots are:"
+ echo "$chroots"
+ exit 1
+elif ! [[ "$requested_chroot" =~ $allowed_filter ]]; then # do not quote the regex
+ echo >&2 "$CHROOT is not a valid dchroot. While it exists, this script may not touch it. Chroot names must match $allowed_filter."
+ exit 1
+fi