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

"""Construct a network namespace with a host0 interface backed by slirp4netns.
"""

import os
import signal
import sys
import typing

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

import linuxnamespaces


def main() -> None:
    mainpid = os.getpid()

    @linuxnamespaces.run_in_fork
    def slirp() -> typing.NoReturn:
        linuxnamespaces.prctl_set_pdeathsig(signal.SIGTERM)
        os.execlp(
            "slirp4netns",
            "slirp4netns",
            "--configure",
            "--disable-host-loopback",
            "%d" % mainpid,
            "host0",
        )

    linuxnamespaces.unshare_user_idmap_nohelper(
        0,
        0,
        linuxnamespaces.CloneFlags.NEWUSER | linuxnamespaces.CloneFlags.NEWNET,
    )
    slirp.start()
    os.execlp(os.environ["SHELL"], os.environ["SHELL"])


if __name__ == "__main__":
    main()
