#!/bin/sh -efu

. girar-sh-functions

usage()
{
	echo >&2 "$PROG: $*"
	echo >&2 "usage: $PROG [<path to directory>]"
	exit 1
}

[ "$#" -le 1 ] ||
	usage 'Too many arguments.'

[ -n "${GIRAR_HOME:-}" ] ||
	fatal 'GIRAR_HOME undefined'

[ -n "${GIRAR_ARCHIVE:-}" ] ||
	fatal 'GIRAR_ARCHIVE undefined'

[ -n "${GIRAR_GEARS:-}" ] ||
	fatal 'GIRAR_GEARS undefined'

cd

if [ "$#" -ge 1 ]; then
	dir="$1"; shift
	printf %s "$dir" |egrep -qs '^[A-Za-z0-9/][-A-Za-z0-9_./]+$' ||
		fatal "$dir: directory name contains unacceptable symbols"
else
	dir=.
fi

[ -z "${dir%%*/}" ] || dir="$dir/"
[ -n "${dir##/*}" -o \
  -z "${dir##$GIRAR_HOME/*}" -o \
  -z "${dir##$GIRAR_ARCHIVE/*}" -o \
  -z "${dir##$GIRAR_GEARS/*}" ] ||
	fatal "$dir: directory does not belong to allowed directory tree"
[ -d "$dir" ] && d="$(readlink -e "$dir")/" ||
	fatal "$dir: directory not available"
p="$(readlink -ev "$GIRAR_HOME")"
a="$(readlink -ev "$GIRAR_ARCHIVE")"
g="$(readlink -ev "$GIRAR_GEARS")"
[ -z "${d##$p/*}" -o \
  -z "${d##$a/*}" -o \
  -z "${d##$g/*}" ] ||
	fatal "$dir: directory does not belong to allowed directory tree"

exec ls -log -- "$dir"
