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

"""Create a pid namespace and provide a matching /proc view. As a consequence,
user and mount namespaces will be unshared as well.

This is similar to unshare --user --pid --mount-proc.
"""

import os
import signal
import sys

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

import linuxnamespaces


def main() -> None:
    namespaces = (
        linuxnamespaces.CloneFlags.NEWUSER
        | linuxnamespaces.CloneFlags.NEWNS
        | linuxnamespaces.CloneFlags.NEWPID
    )
    linuxnamespaces.unshare_user_idmap_nohelper(0, 0, namespaces)
    pid = os.fork()
    if pid == 0:
        linuxnamespaces.prctl_set_pdeathsig(signal.SIGTERM)
        linuxnamespaces.populate_proc("/proc", namespaces)
        os.execlp(os.environ["SHELL"], os.environ["SHELL"])
    else:
        _, status = os.waitpid(pid, 0)
        sys.exit(os.waitstatus_to_exitcode(status))


if __name__ == "__main__":
    main()
