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

"""Vaguely emulate fakeroot using a user namespace that maps the current user
and group to root and the rest of the low range to a subuid range without
performing any chroot. This is similar to unshare --map-root-user --map-auto.
"""

import os
import sys

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

import linuxnamespaces


def main() -> None:
    uidmap = [
        linuxnamespaces.IDMapping(0, os.getuid(), 1),
        linuxnamespaces.IDAllocation.loadsubid("uid").allocatemap(65535, 1),
    ]
    gidmap = [
        linuxnamespaces.IDMapping(0, os.getgid(), 1),
        linuxnamespaces.IDAllocation.loadsubid("gid").allocatemap(65535, 1),
    ]
    linuxnamespaces.unshare_user_idmap(uidmap, gidmap)
    os.execlp(os.environ["SHELL"], os.environ["SHELL"])


if __name__ == "__main__":
    main()
