#!/usr/bin/python3

import subprocess
import tempfile
import glob
import json
import sys
import os


def create_new_manifest(click_file):
    try:
        output = subprocess.check_output(["click", "info", click_file])
    except subprocess.CalledProcessError:
        print >> sys.stderr, "click info %s failed." % click_file
        sys.exit(1)
    manifest = json.loads(output.decode())
    manifest["version"] = manifest["version"] + "+security"
    return manifest


def create_new_click(manifest):
    pwd = os.getcwd()
    directory = tempfile.mkdtemp()
    os.chdir(directory)
    with open("manifest.json", "w") as f:
        f.write(json.dumps(manifest))
    subprocess.call(["click", "build", "."])
    new_click_file = os.path.abspath(glob.glob("*.click")[0])
    subprocess.call(["mv", new_click_file, pwd])
    os.chdir(pwd)
    subprocess.call(["rm", "-r", directory])
    return os.path.abspath(os.path.join(pwd,
                                        os.path.basename(new_click_file)))


def main():
    if len(sys.argv) != 2:
        print("Usage: %s <some-app.click>" % sys.argv[0])
        sys.exit(1)
    click_file = sys.argv[1]
    if not os.path.exists(click_file):
        print("%s does not exist." % click_file)
        sys.exit(1)
    manifest = create_new_manifest(click_file)
    path = create_new_click(manifest)
    print("Updated click package generated at: %s" % path)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print >> sys.stderr, "Aborted."
        sys.exit(1)
