#!/bin/sh

set -e; set -u
. "$(dirname $0)/common"


get_current_user() {
    if [ "$(id -u)" -eq 0 -a ! -z "${SUDO_USER:-}" ]; then
        echo "$SUDO_USER"
    else
        echo "$(whoami)"
    fi
}

set_acl_full() {
    user="$(get_current_user)"
    set +e
    find "$@" -type d -print0 | xargs -0 setfacl -d -m u:www-data:rwX -m u:$user:rwX
    find "$@" -print0 | xargs -0 setfacl -m u:www-data:rwX -m u:$user:rwX
    set -e
}

set_acl_limited() {
    user="$(get_current_user)"
    set +e
    find "$@" -type d -print0 | xargs -0 setfacl -d -m u:www-data:rX -m u:$user:rwX
    find "$@" -print0 | xargs -0 setfacl -m u:www-data:rX -m u:$user:rwX
    set -e
}

remove_acl() {
    setfacl -bR "$@"
}

case "${1:-apply}" in
    apply)
        write_title "Setting up permissions"
        set_acl_full \
            "$APP_DIR/cache" "$APP_DIR/logs" "$BASE_DIR/var" "$APP_DIR/cache/prod/sape" \
            "$WEB_DIR/assets/audios" "$WEB_DIR/assets/files" "$WEB_DIR/assets/images" \
            "$WEB_DIR/assets/images/preview"
    ;;

    remove)
        write_title "Removing permissions"
        remove_acl "$BASE_DIR"
    ;;

    *)
        echo "$0 Invalid operation"
    ;;
esac
