Reimplement loadenv-exec in Python
[tails.git] / config / chroot_local-includes / usr / local / lib / loadenv-exec
blob049ad74c473c06fba0d09d34abb848b40f048167
1 #!/usr/bin/env python3
3 # This script exports environment variables from the file specified in
4 # the ENVFILE argument and then executes the specified command.
6 # If any environment variables from ENVFILE are already set in the
7 # current environment, those are *not* overwritten, so environment
8 # variables set by the caller take precedence over the ones from ENVFILE.
10 # ENVFILE must be null-terminated.
12 import os
13 import sys
14 from pathlib import Path
16 usage = f"{sys.argv[0]} ENVFILE [--] COMMAND [ARG...]"
19 def read_envfile(envfile: str) -> dict:
20     env = dict(os.environ)
21     for line in Path(envfile).read_text().split('\0'):
22         if not line:
23             continue
24         key, value = line.split("=", 1)
25         if key not in env:
26             env[key] = value
27     return env
30 def main():
31     if os.geteuid() != 1000:
32         print(f"{sys.argv[0]: This script must be run as amnesia}", file=sys.stderr)
33         sys.exit(1)
35     if len(sys.argv) < 3:
36         print(usage, file=sys.stderr)
37         sys.exit(1)
39     if sys.argv[2] == "--":
40         del sys.argv[2]
42     env = read_envfile(sys.argv[1])
43     file = sys.argv[2]
44     args = sys.argv[2:]
45     os.execvpe(file, args, env=env)
48 if __name__ == "__main__":
49     main()