#!/bin/sh
# Copyright (c) 2026 Anton Farygin <rider@altlinux.org>
# SPDX-License-Identifier: GPL-2.0-or-later

# Exits 0 inside a container, 1 on a host. Everything this package does — the
# wrappers, the activation, the setuid helper — is meant for a container and is
# a bad idea anywhere else, so all of them ask this one question, and the C
# helper answers it the same way natively.
#
# systemd-detect-virt answers this properly and knows every runtime there is, so
# it goes first — but it lives in systemd, some 23 MB that a build container has
# no other reason to carry, so it cannot be a dependency. Where it is absent,
# three signals in its place, because no single one covers every runtime:
#   * the marker file podman and docker drop in the container,
#   * container= in pid 1's environment, which podman, docker, LXC and
#     systemd-nspawn all set (readable by root only),
#   * a user namespace that maps something other than the whole uid range,
#     which is what every rootless container has and a host never does.

# By absolute path, not through PATH: this answer decides whether anything
# privileged happens, and the caller must not be able to supply it.
[ -x /usr/bin/systemd-detect-virt ] &&
	exec /usr/bin/systemd-detect-virt --quiet --container

[ -e /run/.containerenv ] && exit 0
[ -e /.dockerenv ] && exit 0

# Root only; an unprivileged caller falls through to the uid_map signal. The
# redirection is inside the group so a missing /proc/1/environ is not announced
# by the shell in front of every command the user runs.
{ tr '\0' '\n' </proc/1/environ | grep -q '^container='; } 2>/dev/null && exit 0

# "0 0 4294967295" is the identity mapping every process on a host has; a
# rootless container maps a subrange instead. The status is set in END, since
# `exit` inside a rule runs END anyway and END's own exit would replace it.
awk 'NR == 1 && !($1 == 0 && $2 == 0 && $3 >= 4294967295) { found = 1 }
     END { exit !found }' /proc/self/uid_map 2>/dev/null && exit 0

exit 1
