#!/usr/bin/env python3
# envcp -- read environment of a running process
import argparse
import os
import subprocess

parser = argparse.ArgumentParser()
parser.description = "Get environment variables from a running process."
# This is different from `sudo envcp` as it allows the command to still be run
# with the invoker's privileges.
parser.add_argument("-s", "--sudo",
                        action="store_true",
                        help="read environment with root privileges")
parser.add_argument("pid",
                        metavar="<pid>",
                        type=int,
                        help="process to copy environment from")
parser.add_argument("command",
                        metavar="<command>",
                        nargs="*",
                        default=["/usr/bin/env"],
                        help="command to run with the new environment")
args = parser.parse_args()

try:
    file = "/proc/%d/environ" % args.pid
    with open(file, "rb") as fd:
        buf = fd.read()
except PermissionError as e:
    if args.sudo:
        res = subprocess.run(["sudo", "cat", file], stdout=subprocess.PIPE)
        buf = res.stdout
    else:
        exit("envcp: %s" % e)

env = dict(kv.split(b"=", 1)
           for kv in buf.split(b"\0")
           if kv != b"")

if not env:
    exit("envcp: environment was empty")

os.execvpe(args.command[0], args.command, env)
