#!/usr/bin/python3
"""Keeps customer-installed Node-RED modules when the module set managed by Eurogard is replaced.

    merge-modules <data dir> <staged dir> <manifest> <managed file>

A module is the customer's when it is a dependency in the old package.json and neither part of the new managed set
nor of the legacy packages the new set replaces (or of the set that was managed before). Such modules and the
dependencies they need are copied from the old node_modules into the staged tree, unless the staged tree has its own
version. The merged package.json is written to the staged dir. Prints a JSON report on stdout.
"""
import json
import os
import subprocess
import sys

data, staged, manifest_path, managed_path = sys.argv[1:5]
old_nm = os.path.join(data, "node_modules")
new_nm = os.path.join(staged, "node_modules")


def load(path):
    try:
        with open(path) as f:
            return json.load(f)
    except Exception:
        return {}


def module_dir(root, name):
    return os.path.join(root, *name.split("/"))


manifest = load(manifest_path)
ours = set(manifest.get("managed", []))
previous = set(load(managed_path).get("managed", []))
superseded = set(manifest.get("legacy", [])) | previous

old_pkg = load(os.path.join(data, "package.json"))
new_pkg = load(os.path.join(staged, "package.json"))
old_deps = old_pkg.get("dependencies", {})

user_deps = {n: v for n, v in old_deps.items() if n not in ours and n not in superseded}
dropped = sorted(n for n in old_deps if n in superseded and n not in ours)

# the customer's modules and what they need, resolved in the old tree
needed, seen, todo = [], set(), list(user_deps)
while todo:
    name = todo.pop()
    if name in seen:
        continue
    seen.add(name)
    directory = module_dir(old_nm, name)
    if not os.path.isdir(directory):
        continue
    needed.append(name)
    for dep in load(os.path.join(directory, "package.json")).get("dependencies", {}):
        if dep not in ours:
            todo.append(dep)

copied, native, missing = [], [], sorted(n for n in user_deps if not os.path.isdir(module_dir(old_nm, n)))
for name in sorted(needed):
    target = module_dir(new_nm, name)
    if name in ours or os.path.exists(target):
        continue
    os.makedirs(os.path.dirname(target), exist_ok=True)
    subprocess.run(["cp", "-a", module_dir(old_nm, name), target], check=True)
    copied.append(name)
    for root, _dirs, files in os.walk(target):
        if any(f.endswith(".node") or f == "binding.gyp" for f in files):
            native.append(name)
            break

merged = dict(new_pkg)
deps = dict(new_pkg.get("dependencies", {}))
deps.update(user_deps)
merged["dependencies"] = dict(sorted(deps.items()))
path = os.path.join(staged, "package.json")
with open(path, "w") as f:
    json.dump(merged, f, indent=2)
    f.write("\n")
st = os.stat(data)
os.chown(path, st.st_uid, st.st_gid)

print(json.dumps({"user_modules": sorted(user_deps), "copied": copied, "native": sorted(native),
                  "dropped_legacy": dropped, "missing_in_old_tree": missing}))
