#!/usr/bin/env bash

set -euo pipefail

USER_ID="${USERID:-}"
GROUP_ID="${GROUPID:-}"

if [[ -n "${GROUP_ID}" ]]; then
  CURRENT_GID="$(getent group kirbygroup | cut -d: -f3 || true)"
  if [[ "${GROUP_ID}" != "${CURRENT_GID}" ]]; then
    groupmod --gid "${GROUP_ID}" kirbygroup
  fi
fi

if [[ -n "${USER_ID}" && "${USER_ID}" != "$(id -u www-data)" ]]; then
  usermod --uid "${USER_ID}" www-data
fi

if [[ -n "${GROUP_ID}" ]]; then
  usermod --gid "${GROUP_ID}" www-data
fi

WRITABLE_DIRS=(
  "/var/www/html/content"
  "/var/www/html/media"
  "/var/www/html/site/accounts"
  "/var/www/html/site/cache"
  "/var/www/html/site/logs"
  "/var/www/html/storage"
)

for dir in "${WRITABLE_DIRS[@]}"; do
  mkdir -p "${dir}"
  chown -R www-data:kirbygroup "${dir}"
  chmod -R g+rwX "${dir}"
done

exec "$@"
