#!/bin/bash 

## $Id: lsacl,v 1.5 2015-08-02 10:29:25-07 law Exp law $
# Version 2 -- try to work with getfacl on cygwin
#


shopt -s expand_aliases
alias int=declare\ -i		sub=function  string=declare

gfacl=$(type -P getfacl)

if ! type -f cygwin 2>/dev/null ; then
	_un_=$(type -P uname)
	if		[[ $_un_ ]] ; then _os_=$($_un_ -o);
	elif	[[ -e /proc/sys/kernel ]]; then _os_=Linux; 
	else	_os_=Cygwin; 
	fi
	if		[[ $_os_ =~ Cygwin ]]; then function cygwin () { return 0; }
	else	function cygwin () { return 1; }
	fi
	unset _un_ _os_
	export -f cygwin
fi

if cygwin 2>/dev/null ;then 
	[[ $gfacl ]] || { printf "FATAL: Cannot find getfacl in path\n"; exit 1; }
	sub gfacl () { "$gfacl" "$@"; }
else										## linux version has broken semantics requiring "-p"
	sub gfacl () { "$gfacl" -p "$@" ; }
fi

export -f gfacl


sub facl2str {
	string fn=${1:?"Need pathname"}
	string s1='/^\#.*$/d; /^\s*$/d; s/\s*#.*$//; s/^(.)(ser|roup|ask|ther):/\1:/; y/\n/,/'
	string facl=$(gfacl -a "$fn"|sed -r "$s1"|tr "\n" ",")
	facl=${facl%,}
	string dacl=$(gfacl -d "$fn"|sed -r "s/^default://; $s1"|tr "\n" ",")
	dacl=${dacl%,}
	printf "[%s/%s]\n" "$facl" "$dacl"
}



int acllen=0 maxfnln=0
#for fn in "$@" ; do if ((maxfnln<${#fn})); then maxfnln=${#fn}; fi ; done

sub acl_str () {
	if cygwin ;then 
		perm=$(facl2str "$fn")
	else 
		qfn=$(printf "%q " "$fn")
		out="$(chacl -l "$fn")"
		perm="${out#$qfn}"
	fi
	printf "%s\n" "$perm"
}


for fn in "$@"; do
	int max=40
	perm=$(acl_str "$fn")
	int len=${#perm}
	if ((len>_acl_len_)); then acllen=len; fi
	if ((acllen>max));		then acllen=max; fi
	printf "%-${acllen}s %s\n" "$perm" "$fn"
done
