#!/bin/sh
set -eu

normalize_bool() {
    input="$(echo "$1" | tr A-S a-s)"
    if [ "$input" = "" ] || [ "$input" = "0" ] || [ "$input" = "false" ]; then
        echo 0
    else
        echo 1
    fi
}

str_contains() {
    haystack=$1
    needle=$2

    test "${haystack#*"$needle"}" != "$haystack"
}

POSTMILL_SKIP_ACL=$(normalize_bool "${POSTMILL_SKIP_ACL:-}")

# Make sure stdout and stderr are writeable
if [ $(id -u) -eq 0 ]; then
    chmod go+w /proc/self/fd/1 /proc/self/fd/2
fi

if [ "${SU_USER:-}" != "" ] && [ $(id -u) -eq 0 ]; then
    # Ensure writeable directories exist
    mkdir -p $POSTMILL_WRITE_DIRS

    # Grant file permissions via ACL
    if str_contains "$1" postmill-startup && [ $POSTMILL_SKIP_ACL -eq 0 ]; then
        setfacl -R -m u:www-data:rwX -m u:"$SU_USER":rwX $POSTMILL_WRITE_DIRS || true
        setfacl -dR -m u:www-data:rwX -m u:"$SU_USER":rwX $POSTMILL_WRITE_DIRS || true
    fi

    # Drop root privileges
    if command -v su-exec > /dev/null; then
        set -- su-exec "$SU_USER" "$@"
    else
        set -- gosu "$SU_USER" "$@"
    fi
fi

exec docker-php-entrypoint "$@"
