#!/usr/bin/env python3
"""Replace the engine in an existing product folder. Never writes in data/.

    bin/update-engine DIR                 install this engine into DIR
    bin/update-engine DIR --hashes OUT    also write data/'s hash list, before and after, to OUT

Run it from the NEW engine (the app runs the one it ships; a developer runs
this repository's engine/bin/update-engine). It copies the new engine to
engine.new/, swaps it in for engine/, deletes the old one, and rewrites the
engine-owned files at the top (folder.py says which). It hashes every file in
data/ before and after; if one differs it exits 2 and says which, because
that is the one promise an update makes.

Exit 0 and one line; exit 1 and one line when DIR is not a product folder.
Standard library only.
"""
import json
import os
import shutil
import sys

sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import folder  # noqa: E402

ENGINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def main(argv):
    args = list(argv)
    if not args or args[0] in ("-h", "--help"):
        print(__doc__.strip())
        return 0 if args else 1
    top = os.path.abspath(os.path.expanduser(args.pop(0)))
    out = None
    if args[:1] == ["--hashes"] and len(args) == 2:
        out = args[1]
    elif args:
        print("usage: bin/update-engine DIR [--hashes OUT]", file=sys.stderr)
        return 1
    data, engine = os.path.join(top, "data"), os.path.join(top, "engine")
    if not os.path.isfile(os.path.join(data, "now.md")) or not os.path.isdir(engine):
        print("%s is not a product folder (needs engine/ and data/now.md)" % top, file=sys.stderr)
        return 1
    if os.path.realpath(engine) == os.path.realpath(ENGINE):
        print("%s already runs this engine; run the new engine's update-engine" % top, file=sys.stderr)
        return 1
    before = folder.hashes(data)
    staged, old = engine + ".new", engine + ".old"
    for leftover in (staged, old):
        shutil.rmtree(leftover, ignore_errors=True)
    folder.copy_engine(ENGINE, staged)
    os.rename(engine, old)
    os.rename(staged, engine)
    shutil.rmtree(old)
    skills = folder.write_top(top, folder.embedder(ENGINE))
    after = folder.hashes(data)
    if out:
        with open(out, "w", encoding="utf-8") as f:
            json.dump({"before": before, "after": after}, f, indent=1, sort_keys=True)
    changed = sorted(p for p in set(before) | set(after) if before.get(p) != after.get(p))
    if changed:
        print("data/ changed during the update: %s" % ", ".join(changed), file=sys.stderr)
        return 2
    print("%s: engine replaced, %d skills, data/ unchanged (%d files)" % (top, len(skills), len(after)))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
