#!/bin/sh -efu

. girar-sh-functions
. shell-quote
. shell-args

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

# Abort if no non-empty repository list available.
[ -s "$GIRAR_REPO_LIST" ] ||
	fatal 'Sorry, list of available repositories is not available'

quiet=
case "${1-}" in
	--help)
	        cat <<EOF
Usage: $PROG --list
   or: $PROG <repository> [{<package>|@<group>} {check|show}]
   or: $PROG <repository> [{<package>|@<group>} {add|del|leader|replace} {<login>|@<group>}...]
   or: $PROG <repository>
Valid repositories are: $(tr -s '\n' ' '<"$GIRAR_REPO_LIST")
If no package is given, read commands from stdin, one command per line.
See http://www.altlinux.org/Incoming/acl for details.
EOF
		exit 0
		;;
	--list)
		cat -- "$GIRAR_REPO_LIST"
		exit 0
		;;
	--quiet)
		quiet="$1"
		shift
		;;
esac

nqueued=0
add_acl_cmd()
{
	printf "$@" | girar-acl-apply-changes $quiet "$repository" "$tmpdir" 3>&-
	printf >&3 "$@"
	nqueued="$(($nqueued+1))"
}

show_acl()
{
	[ "$#" -eq 0 ] ||
		usage 'Too many arguments.'
	girar-acl-show "$repository" "$item" "$tmpdir" 3>&-
}

rc=0
parse_cmd()
{
	[ "$#" -ge 2 ] ||
		show_usage 'Not enough arguments.'

	local item="$1"; shift
	local action="$1"; shift

	rc=0
	case "$action" in
		show)
			show_acl "$@"
			return ;;
		check)
			girar-check-perms "$item" "$repository" 3>&- || rc=1
			return ;;
	esac

	add_acl_cmd '%s\t%s\t%s\n' "$item" "$action" "$*"
}

[ "$#" -ge 1 ] ||
	show_usage 'Not enough arguments.'

repository="$1"
shift

repository="$(girar-normalize-repo-name "$repository")"

. girar-sh-tmpdir

# Copy all current acl files to tmpdir.
cd "$GIRAR_ACL_CONF_DIR"
flock -s . \
find -maxdepth 1 -type f -name 'list.*' \
        -exec cp -at "$tmpdir" -- \{\} \+
cd - > /dev/null

# First line is a repository name
exec 3>"$tmpdir/cmd"
echo "$repository" >&3

# If caller specified arguments, parse them,
# otherwise parse stdin line by line.
if [ $# -eq 0 ]; then
	message 'Go ahead and type your commands' >&2
	while read -r line; do
		parse_cmd $line
	done
else
	parse_cmd "$@"
fi

exec 3>&-

[ $nqueued -gt 0 ] || exit $rc

girar-connect-stdout "$GIRAR_ACL_SOCKET" cat < "$tmpdir/cmd"

[ -n "$quiet" ] ||
	message "$nqueued command(s) queued"

exit $rc
