#!/usr/bin/env bash
# Drops from root (needed to read the prebuilt toolchain under /opt) to a
# user matching the host's UID/GID, so anything written into the
# bind-mounted repo (engine/build_ext, engine/.build-output, ...) is owned
# by the host user instead of root.
set -euo pipefail

USER_UID="${HOST_UID:-1000}"
USER_GID="${HOST_GID:-1000}"

groupadd -g "$USER_GID" builder 2>/dev/null || true
useradd -u "$USER_UID" -g "$USER_GID" -m -s /bin/bash builder 2>/dev/null || true

# /workspace (the bind-mounted repo) may actually be owned by a group the
# host user only has via *supplementary* membership rather than their
# primary GID above - e.g. a VirtualBox vboxsf shared folder, which shows
# up as root:vboxsf on the host and would otherwise be inaccessible to
# `builder` here (falls through to "other", which vboxsf's default mode
# leaves with no permissions at all). Join whatever group actually owns
# /workspace too, if it differs.
WORKSPACE_GID="$(stat -c %g /workspace 2>/dev/null || true)"
if [ -n "$WORKSPACE_GID" ] && [ "$WORKSPACE_GID" != "$USER_GID" ]; then
    groupadd -g "$WORKSPACE_GID" workspace 2>/dev/null || true
    usermod -aG "$WORKSPACE_GID" builder 2>/dev/null || true
fi

exec gosu builder "$@"
