#!/bin/sh
# Copyright (C) 2010 - 2018 FARGOS Development, LLC
# lsbt - List available backing tree names/paths
# $Id$

defaultRootPath="${BT_ROOT_PATH:-/opt/backingTrees}"
separator=":"
fullPath=1

btRootList=""

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [{-n|-f}] [{-s separator} | --space] {--btroot backingTreeRoot}\n" "${0}" >&2
		printf "  -n = list only backing tree name\n" >&2
		printf "  -f = list full path name of backing tree (default)\n" >&2
		printf "  --btroot = backing tree root, default is \"%s\", set by BT_ROOT_PATH\n" "${defaultRootPath}" >&2
		printf "  default output separator: \"%s\"\n" "${separator}" >&2
		exit 1
		;;
	-n)
		fullPath=0
		;;
	-f)
		fullPath=1
		;;
	-s)
		separator="${2}"
		shift
		;;
	--space)
		separator=" "
		;;
	-btroot | -bt | --btroot | --bt)
		btRootList="${btRootList}${btRootList:+:}${2}"
		shift
		;;
	-*)
		printf "%s: unrecognized option \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	*)
		printf "%s: unrecognized argument \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	esac
	shift
done

if test -z "${btRootList}"
then # not set via command line
	btRootList="${defaultRootPath}"
fi

# convert colon-separated path into distinct elements
rootList=`pathedit --space ${btRootList}`

result=""
for btRoot in ${rootList}
do
	for f in "${btRoot}"/*/BuildEnv
	do
		if test -r "${f}"
		then
			d=`dirname "${f}"`
			if test ${fullPath} -eq 0
			then
				d=`basename "${d}"`
			fi
			result="${result}${result:+${separator}}${d}"
		fi
	done
done
echo ${result}
exit 0
