# exec-drop.sh — Privilege drop setup, WSL2 keepalive, and single-shot exec.
# shellcheck shell=bash
# Requires: die (from helpers.sh), CMD_PREAMBLE (from init-scripts.sh).
# Exports: SETPRIV_ARGS (array used by _exec_single_shot).
# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.

SETPRIV_ARGS=()

# _setup_setpriv_args: verify setpriv is available and build privilege-drop argument array.
# Explicitly clears all capability sets so even if no-new-privileges is bypassed,
# the devcage user has zero capabilities.
_setup_setpriv_args() {
    if ! command -v setpriv >/dev/null 2>&1; then
        die "setpriv not found — cannot drop privileges safely"
    fi
    SETPRIV_ARGS=(--reuid=devcage --regid=devcage --init-groups
                  --inh-caps=-all --ambient-caps=-all --bounding-set=-all)
}

# _start_wsl2_keepalive: background loop to prevent WSL2 VM idle-shutdown.
# Docker Desktop (WSL2 backend) may stop the VM after a period of
# inactivity, killing the container.  A lightweight background loop
# touches a file on /dev/shm (tmpfs — in-memory, no disk I/O) every
# 60 seconds to keep the VM alive.  The process uses default OOM and
# scheduling priority — its ~7 KB RSS makes it a naturally low OOM
# target, and letting it die under extreme pressure is preferable to
# a zombie container that appears alive with no workload running.
# Automatically cleaned up when Docker SIGTERMs all PIDs on exit.
_start_wsl2_keepalive() {
    if [ -d /dev/shm ]; then
        (
            trap 'exit 0' TERM
            exec setpriv --reuid=devcage --regid=devcage --init-groups \
                 --inh-caps=-all --ambient-caps=-all --bounding-set=-all -- \
                 sh -c 'while :; do sleep 60; touch /dev/shm/.devcage-keepalive 2>/dev/null; done'
        ) &
    fi
}

# _exec_single_shot: exec into the agent command (legacy / --no-reuse mode).
# Never returns on success. Calls die() if exec itself fails.
_exec_single_shot() {
    if [ $# -eq 0 ]; then
        echo "✓ Sandbox ready | Workspace: ${HOST_WORKSPACE:-unknown}" >&2
        echo >&2
        exec setpriv "${SETPRIV_ARGS[@]}" -- bash
    elif [ "$CMD_PREAMBLE" != "" ]; then
        exec setpriv "${SETPRIV_ARGS[@]}" -- bash -c "$CMD_PREAMBLE"'exec "$@"' _ "$@"
    else
        exec setpriv "${SETPRIV_ARGS[@]}" -- "$@"
    fi
    die "exec setpriv failed — refusing to continue as root (UID=$(id -u))"
}
