#!/bin/bash
# Runs as root at container start (before any `docker exec -u vscode` from VS Code).
# The docker.sock's GID is only known once the host socket is actually bind-mounted,
# so it can't be baked in at image build time - it must be reconciled here, at runtime.
set -e

if [ -S /var/run/docker.sock ]; then
  SOCK_GID=$(stat -c '%g' /var/run/docker.sock)
  CURRENT_GID=$(getent group docker | cut -d: -f3)
  if [ -n "$SOCK_GID" ] && [ "$SOCK_GID" != "$CURRENT_GID" ]; then
    EXISTING_GROUP=$(getent group "$SOCK_GID" | cut -d: -f1)
    if [ -n "$EXISTING_GROUP" ]; then
      # GID is already taken by another group (e.g. GID 0/root - Docker Desktop for
      # Mac/Windows owns the socket this way inside its VM), so join that group
      # instead of trying to reassign it to 'docker'.
      usermod -aG "$EXISTING_GROUP" vscode
    else
      groupmod -g "$SOCK_GID" docker
    fi
  fi
fi

exec gosu vscode "$@"
