#! /usr/bin/python3
#
# Copyright (C) 2023 Cloud Software Group
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only. with the special
# exception on linking described in file LICENSE.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.


import pwd, subprocess, sys

cmd = ["/usr/libexec/xen/bin/pygrub"]

# Get the usage string. We can't use check_output() because the exit status isn't 0
pygrub_usage = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True).communicate()[1]

for arg in sys.argv[1:]:
    # Catch the synthetic --domid argument and turn it into --runas
    argname_domid = "--domid="
    if arg.startswith(argname_domid):
        domid = int(arg[len(argname_domid):])
        uid = pwd.getpwnam('qemu_base').pw_uid + domid
        cmd += ["--runas=" + str(uid)]
    else:
        cmd += [arg]

sys.exit(subprocess.call(cmd))
