#!/bin/sh
set -e

# ── Git identity ─────────────────────────────────────────────────────
# Agents commit code inside the container. Without a git identity,
# commits fail or use garbage defaults. Fail loudly at startup so the
# operator knows immediately.
if [ -z "$GIT_USER_NAME" ]; then
    echo "FATAL: GIT_USER_NAME is not set. Export it in your environment or docker-compose.yml." >&2
    exit 1
fi
if [ -z "$GIT_USER_EMAIL" ]; then
    echo "FATAL: GIT_USER_EMAIL is not set. Export it in your environment or docker-compose.yml." >&2
    exit 1
fi

# Set git identity globally so it persists for all shells (docker exec, etc.),
# not just the entrypoint process tree.
git config --global user.name "$GIT_USER_NAME"
git config --global user.email "$GIT_USER_EMAIL"

# Also set env vars for backwards compatibility.
export GIT_AUTHOR_NAME="$GIT_USER_NAME"
export GIT_COMMITTER_NAME="$GIT_USER_NAME"
export GIT_AUTHOR_EMAIL="$GIT_USER_EMAIL"
export GIT_COMMITTER_EMAIL="$GIT_USER_EMAIL"

# ── Frontend native deps ────────────────────────────────────────────
# The project repo is bind-mounted from the host, so node_modules/
# may contain native binaries for the wrong platform (e.g. darwin
# binaries on a Linux container). Reinstall to get the right ones.
if [ -d /workspace/frontend ] && [ -f /workspace/frontend/package.json ]; then
    echo "Installing frontend dependencies for container platform..."
    cd /workspace/frontend && npm ci --prefer-offline 2>/dev/null || true
    cd /workspace
fi

exec "$@"
