#!/usr/bin/python3
# Copyright 2024 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: LGPL-2.0-or-later

"""Map all available ranges from /etc/subuid and /etc/subgid as identity and
run a given command with all capabilities (including CAP_DAC_OVERRIDE)
inherited. This is vaguely similar to running:

    unshare --map-auto --map-user=$(id -u) --map-group=$(id -g) --keep-caps
"""

import os
import sys

if __file__.split("/")[-2:-1] == ["examples"]:
    sys.path.insert(0, "/".join(__file__.split("/")[:-2]))

import linuxnamespaces


def main() -> None:
    # Construct an identity mapping of all available user/group ids
    uidmap = [
        linuxnamespaces.IDMapping.identity(os.getuid()),
        *(
            linuxnamespaces.IDMapping(start, start, count)
            for start, count
            in linuxnamespaces.IDAllocation.loadsubid("uid").ranges
        ),
    ]
    gidmap = [
        linuxnamespaces.IDMapping.identity(os.getgid()),
        *(
            linuxnamespaces.IDMapping(start, start, count)
            for start, count
            in linuxnamespaces.IDAllocation.loadsubid("gid").ranges
        ),
    ]
    linuxnamespaces.unshare_user_idmap(uidmap, gidmap)

    # We haven't changed uid. We still are non-root, but the user namespace
    # augmented our permitted and effective capabilities! Add them to the
    # inheritable set.
    capabilities = linuxnamespaces.CapabilitySets.get()
    capabilities.inheritable = capabilities.permitted & capabilities.effective
    capabilities.set()
    # Add all inheritable capabilities to the ambient set.
    linuxnamespaces.prctl_raise_ambient_capabilities(capabilities.inheritable)
    if len(sys.argv) > 1:
        os.execvp(sys.argv[1], sys.argv[1:])
    else:
        os.execvp(os.environ["SHELL"], [os.environ["SHELL"]])


if __name__ == "__main__":
    main()
