#!/usr/bin/env python3
# envdiff - compare environment variables between two shells, or a file and the current env
# Usage: envdiff FILE1 [FILE2] | envdiff --shell bash --shell zsh | envdiff FILE (vs current env)
import argparse, os, subprocess, sys

def parse_env_file(path):
    env = {}
    with open(path, errors="replace") as f:
        for line in f:
            line = line.rstrip("\n")
            if "=" in line and not line.startswith("#"):
                k, v = line.split("=", 1)
                env[k] = v
    return env

def shell_env(shell):
    r = subprocess.run([shell, "-c", "env"], capture_output=True, text=True, timeout=30)
    if r.returncode != 0:
        print("envdiff: shell %r failed: %s" % (shell, r.stderr.strip()), file=sys.stderr)
        sys.exit(1)
    env = {}
    for line in r.stdout.splitlines():
        if "=" in line:
            k, v = line.split("=", 1)
            env[k] = v
    return env

def diff(a, b, la, lb, only_changed=False):
    added = sorted(set(b) - set(a))
    removed = sorted(set(a) - set(b))
    changed = sorted(k for k in set(a) & set(b) if a[k] != b[k])
    same = sorted(k for k in set(a) & set(b) if a[k] == b[k])
    print("envdiff: %s (%d vars) vs %s (%d vars)" % (la, len(a), lb, len(b)))
    if added:
        print("only in %s (%d):" % (lb, len(added)))
        for k in added:
            print("  + %s=%s" % (k, b[k]))
    if removed:
        print("only in %s (%d):" % (la, len(removed)))
        for k in removed:
            print("  - %s=%s" % (k, a[k]))
    if changed:
        print("changed (%d):" % len(changed))
        for k in changed:
            print("  ~ %s:\n      %s: %s\n      %s: %s" % (k, la, a[k], lb, b[k]))
    if not only_changed:
        print("unchanged: %d" % len(same))
    return 0 if not (added or removed or changed) else 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        f1 = os.path.join(d, "a.env"); f2 = os.path.join(d, "b.env")
        open(f1, "w").write("FOO=1\nBAR=same\nOLD=gone\n")
        open(f2, "w").write("FOO=2\nBAR=same\nNEW=here\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), f1, f2],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "FOO" in out.stdout and "NEW" in out.stdout and "OLD" in out.stdout
        assert "changed (1)" in out.stdout
        print("envdiff selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="envdiff",
        description="Compare environment variables between two shells, two files, or a file and the current env.")
    ap.add_argument("files", nargs="*", help="env files (KEY=VALUE per line); one file compares against the current env")
    ap.add_argument("--shell", action="append", default=[], metavar="SHELL",
                    help="shell to dump env from (repeat twice to compare two shells)")
    ap.add_argument("--only-changed", action="store_true", help="hide the unchanged count")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if len(a.shell) == 2:
        return diff(shell_env(a.shell[0]), shell_env(a.shell[1]), a.shell[0], a.shell[1], a.only_changed)
    if len(a.shell) == 1:
        return diff(shell_env(a.shell[0]), dict(os.environ), a.shell[0], "current env", a.only_changed)
    if len(a.files) == 2:
        return diff(parse_env_file(a.files[0]), parse_env_file(a.files[1]),
                    a.files[0], a.files[1], a.only_changed)
    if len(a.files) == 1:
        return diff(parse_env_file(a.files[0]), dict(os.environ),
                    a.files[0], "current env", a.only_changed)
    ap.error("give two files, one file, or --shell twice")
    return 2

if __name__ == "__main__":
    sys.exit(main())
