# uid-remap.sh — Container UID matching and workspace ownership fix.
# shellcheck shell=bash
# Sets TARGET_UID and CURRENT_UID globals used by cache-setup.sh.
# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.

TARGET_UID=""
CURRENT_UID=""

# _remap_uid: match container devcage user's UID to the host user's UID.
# This ensures files created in /workspace are owned by the calling
# user on the host, not by a mismatched UID.
# Sets globals: TARGET_UID, CURRENT_UID
_remap_uid() {
    TARGET_UID="${HOST_UID:-1000}"
    if ! [[ "$TARGET_UID" =~ ^[0-9]+$ ]]; then
        warn "HOST_UID='${TARGET_UID}' is not numeric — falling back to 1000"
        TARGET_UID=1000
    fi

    if ! id devcage >/dev/null 2>&1; then
        die "devcage user does not exist — image may be corrupt"
    fi

    CURRENT_UID="$(id -u devcage)"

    if [ "$TARGET_UID" != "0" ] && [ "$TARGET_UID" != "$CURRENT_UID" ]; then
        local _existing_user
        _existing_user="$(getent passwd "$TARGET_UID" 2>/dev/null | cut -d: -f1 || true)"
        if [ "$_existing_user" != "" ] && [ "$_existing_user" != "devcage" ]; then
            usermod -u 99999 "$_existing_user" 2>/dev/null || warn "could not relocate user $_existing_user from UID $TARGET_UID"
        fi
        if ! usermod -u "$TARGET_UID" devcage 2>/dev/null; then
            warn "usermod -u ${TARGET_UID} devcage failed — continuing with UID ${CURRENT_UID}"
            warn "files in /workspace may have incorrect ownership on the host"
        fi
        # chown may partially fail on bind-mounted dirs (e.g. macOS Docker
        # Desktop) — warn so failures are visible in logs rather than
        # silently ignoring them (#11).
        if ! chown -Rh devcage:devcage /home/devcage 2>/dev/null; then
            warn "chown /home/devcage partially failed (bind-mount? — usually harmless)"
        fi
        # Homebrew is owned by devcage — update after UID change so
        # `brew install` works at runtime.
        if [ -d /home/linuxbrew ]; then
            chown -Rh devcage:devcage /home/linuxbrew 2>/dev/null || true
        fi
    fi
}

# _fix_workspace_ownership: ensure /workspace files are owned by the devcage user.
# Quick depth-2 probe; full recursive chown only when a mismatch is found.
# Marker file avoids repeated no-op chowns on filesystems where chown
# is ineffective (Docker Desktop for Windows/macOS grpcfuse/VirtioFS mounts).
_fix_workspace_ownership() {
    local _dc_uid _ws_marker _skip_ws_probe
    _dc_uid="$(id -u devcage)"
    _ws_marker="/workspace/.devcage/local/.chown-uid"
    _skip_ws_probe=0
    if [ "${HOST_OS:-}" = "windows" ] || [ "${HOST_OS:-}" = "macos" ]; then
        if [ -f "$_ws_marker" ] && [ "$(cat "$_ws_marker" 2>/dev/null)" = "$_dc_uid" ]; then
            _skip_ws_probe=1
        fi
    fi
    if [ "$_skip_ws_probe" = "0" ]; then
        if find /workspace -maxdepth 2 -not -user "$_dc_uid" -print -quit 2>/dev/null | grep -q .; then
            if [ ! -f "$_ws_marker" ] || [ "$(cat "$_ws_marker" 2>/dev/null)" != "$_dc_uid" ]; then
                if [ "${HOST_OS:-}" = "windows" ] || [ "${HOST_OS:-}" = "macos" ]; then
                    # On Docker Desktop (WSL2/VirtioFS), chown is cosmetic — the mount
                    # driver handles actual file permissions. Set marker immediately and
                    # run deep chown in background to avoid blocking the ready marker.
                    _entrypoint_log "fixing /workspace ownership in background (files not owned by UID $_dc_uid)"
                    mkdir -p /workspace/.devcage/local 2>/dev/null || true
                    printf '%s\n' "$_dc_uid" > "$_ws_marker" 2>/dev/null || true
                    ( chown -Rh devcage:devcage /workspace 2>/dev/null || true ) &
                else
                    # On Linux, chown has real effect — run synchronously.
                    _entrypoint_log "fixing /workspace ownership (files not owned by UID $_dc_uid)"
                    chown -Rh devcage:devcage /workspace 2>/dev/null || \
                        warn "chown /workspace partially failed — some files may not be writable"
                    mkdir -p /workspace/.devcage/local 2>/dev/null || true
                    printf '%s\n' "$_dc_uid" > "$_ws_marker" 2>/dev/null || true
                fi
            fi
        fi
    fi
}
