#!/usr/bin/env python

import os
import sys
import copy
import datetime
import yaml
import json

def main():
    if len(sys.argv) != 2:
        raise SystemExit(
            "Usage: {} <yaml template file to rewrite>".format(
                sys.argv[0],
            ),
        )

    name = sys.argv[1]
    template = name + ".template"
    generated = name + ".generated"
    with open(template) as f:
        obj = yaml.safe_load(f)

    # GitHub gets angry if we have things that don't conform to their schema.
    # Get rid of all this stuff now that it has served its purpose.
    del obj["anchors"]

    with open(name) as f:
        existing_obj = yaml.safe_load(f)

    if obj == existing_obj:
        raise SystemExit("Generated file already up-to-date.")

    with open(generated, "w") as g:
        g.write(HEADER.format(
            now=datetime.datetime.now().isoformat(),
            command="{!r} {!r}".format(*sys.argv),
            ),
        )
        # Serialize with json because json won't accidentally re-insert the
        # anchors that we're trying to strip out.
        json.dump(obj, g)
    os.rename(generated, name)

HEADER = """\
# DO NOT EDIT!  This file was automatically generated.
# Generated at: {now}
# Generated by: {command}

"""

if __name__ == '__main__':
    main()
