#!/usr/bin/env python3
"""Script for creating a Flatpak manifest out of a template."""
# pylint: disable=invalid-name

import json
import os
import subprocess
import sys


def generate():
    """Creates the manifest file."""
    basedir = sys.argv[3]
    gst_version = sys.argv[4]
    branchname = sys.argv[5]
    with open(sys.argv[1], "r") as tf:
        template = json.load(tf)

    if branchname == "stable":
        del template["desktop-file-name-prefix"]
    elif branchname == "master":
        template["desktop-file-name-prefix"] = "(Rolling) "
    else:
        template["desktop-file-name-prefix"] = "(%s) " % branchname

    print("-> Generating %s against GStreamer %s" % (sys.argv[2], gst_version))

    for module in template["modules"]:
        if module["sources"][0]["type"] != "git":
            continue

        if module["name"].startswith("gst"):
            module["sources"][0]["branch"] = gst_version
            if gst_version != "master":
                continue

        repo = os.path.join(basedir, module["name"])
        if not os.path.exists(os.path.join(repo, ".git")):
            print("-> Module: %s using online repo: %s" % (
                module["name"], module["sources"][0]["url"]))
            continue

        os.chdir(repo)
        branch = subprocess.check_output(r"git branch 2>&1 | grep \*",
                                         shell=True).decode(
                                             "utf-8").split(' ')[1][:-1]

        repo = "file://" + repo
        print("-> Module: %s repo: %s branch: %s" % (module["name"],
                                                     repo, branch))
        module["sources"][0]["url"] = repo
        module["sources"][0]["branch"] = branch

    with open(sys.argv[2], "w") as of:
        print(json.dumps(template, indent=4), file=of)

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print("call with: %s <template_file> <outfile> <basedir> <gst-version> <branchname>" %
              sys.argv[0])
        exit(1)

    generate()
