#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash
set -e

fspath="$1"
acluser="$2"
aclgroup="$3"
aclmode="$4"
shift 4

# ensure any things created by the user script have the desired mode.
# chmod doesn't work on symlinks, so we *have* to use this umask approach.
decmask=$(( 0777 - "$aclmode" ))
octmask=$(printf "%o" "$decmask")
umask "$octmask"

# try to chmod/chown the result even if the user script errors
set +e
("$@")
user_status=$?
set -e

# claim ownership of the new thing (DON'T traverse symlinks)
chown --no-dereference "$acluser:$aclgroup" "$fspath"
# AS LONG AS IT'S NOT A SYMLINK, try to fix perms in case the entity existed before this script was called
if ! test -L "$fspath"
then
  chmod "$aclmode" "$fspath"
fi

exit "$user_status"
