#!/bin/sh
# Copyright (C) 2012 - 2018 FARGOS Development, LLC
# $Id$
# eliminate redundant path elements
# NOTE:  this shell script implementation has an alternate native implementation
initialPath=""
pathSeparator=':'
mustExist=0

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [{{-s separator} | --space}] [-x] dir [...]\n" "${0}" >&2
		printf "  -s = specifies output separator for path elements, defaults to \"%s\"\n" "${pathSeparator}" >&2
		printf "  --space = use space as output separator\n" >&2
		printf "  -x = only include filesystem elements that exist\n" >&2
		exit 1
		;;
	-s)
		pathSeparator="${2}"
		shift
		;;
	-space | --space)
		pathSeparator=' '
		;;
	-x)
		mustExist=1
		;;
	*)
		elem=`echo ${1} | sed -e 's/:/ /g'`
		initialPath="${initialPath}${initialPath:+ }${elem}"
		;;
	esac
	shift
done

didElems=""
newPath=""
for elem in ${initialPath}
do
	if test ${mustExist} -eq 1
	then
		if test ! -e "${elem}"
		then # doesn't exist, skip to next element
			continue
		fi
	fi
	did=`expr "_${didElems}_" : '.*'@${elem}@`
	if test "${did}" -eq 0
	then
		newPath="${newPath}${newPath:+${pathSeparator}}${elem}"
		didElems="${didElems}@${elem}@"
	fi
done
echo ${newPath}
exit 0
