#!/usr/bin/env bash
set -euo pipefail

GROUP="www-data"

usage() {
  echo "Usage: $0 /path/to/project"
  exit 1
}

if [[ $# -ne 1 ]]; then
  usage
fi

TARGET="$1"

if [[ ! -d "$TARGET" ]]; then
  echo "Error: '$TARGET' is not a directory"
  exit 1
fi

if ! command -v setfacl >/dev/null 2>&1; then
  echo "Error: setfacl is not installed"
  echo "Install it with: sudo apt-get install acl"
  exit 1
fi

echo "Fixing permissions under: `realpath $TARGET`"

# Shared group for everything
chgrp -R "$GROUP" "$TARGET"

# Directories: group writable + setgid so new entries inherit group
find "$TARGET" -type d -exec chmod 2775 {} +

# Regular files: rw-rw-r--
find "$TARGET" -type f -exec chmod 664 {} +

# Restore execute bits for common executable files
# Existing executable files for owner -> make executable for group too
find "$TARGET" -type f -perm -100 -exec chmod 775 {} +

# Common project script locations
for dir in \
  "$TARGET/api/vendor/bin" \
  "$TARGET/html/node_modules/.bin"
do
  if [[ -d "$dir" ]]; then
    find "$dir" -type f -exec chmod 775 {} +
  fi
done

# ACLs: group rwx on directories and inherited entries
setfacl -R -m g:${GROUP}:rwx "$TARGET"
setfacl -R -m d:g:${GROUP}:rwx "$TARGET"
setfacl -R -m d:o::rx "$TARGET"

echo "Done."