#!/bin/bash
# This is brought from jupyter docker-stacks:
# https://github.com/jupyter/docker-stacks/blob/main/docker-stacks-foundation/fix-permissions
# set permissions on a directory
# after any installation, if a directory needs to be (human) user-writable,
# run this script on it.
# It will make everything in the directory owned by the group ${SYSTEM_GID}
# and writable by that group.

# uses find to avoid touching files that already have the right permissions,
# which would cause massive image explosion

# right permissions are:
# group=${SYSEM_GID}
# AND permissions include group rwX (directory-execute)
# AND directories have setuid,setgid bits set

set -e

for d in "$@"; do
    find "${d}" \
        ! \( \
            -group "${SYSTEM_GID}" \
            -a -perm -g+rwX \
        \) \
        -exec chgrp "${SYSTEM_GID}" -- {} \+ \
        -exec chmod g+rwX -- {} \+
    # setuid, setgid *on directories only*
    find "${d}" \
        \( \
            -type d \
            -a ! -perm -6000 \
        \) \
        -exec chmod +6000 -- {} \+
done
