#!/usr/bin/python3

import ast

FILE = "../larch/apps.py"

# find the LarchApps variable without importing eveythings
with open(FILE) as f:
    content = f.read()
    nodes = ast.parse(content)
    for node in ast.walk(nodes):
        if isinstance(node, ast.Assign):
            s = ast.get_source_segment(content, node)
            if "LarchApps" in s:
                ss = ast.unparse(node.value)
                break

nodes = ast.parse(ss)
LarchApps = {}
for node in ast.walk(nodes):
    if isinstance(node, ast.Dict):
        for k, v in zip(node.keys, node.values):
            LarchApps[k.value] = {}
            for kw in v.keywords:
                LarchApps[k.value][kw.arg] = kw.value.value

for i in LarchApps:
    app_name = LarchApps[i]["name"]
    icon = LarchApps[i]["icon"]
    cmd = LarchApps[i]["script"]
    if "is_wxapp" in LarchApps[i]:
        terminal = not LarchApps[i]["is_wxapp"]
    else:
        terminal = False

    if cmd.startswith("_"):
        continue

    # compute the desktop fiename
    filename = f"{app_name.lower().replace(' ', '-')}.desktop"
    filename = filename if "larch-" in filename else f"larch-{filename}"
    print(filename)

    # compute the xdg categories
    categories = ["Science", "Physics", "Chemistry"]
    if terminal:
        categories.insert(0, "ConsoleOnly")

    # on Debian larch -> larch_cli
    if cmd == "larch":
        cmd = "larch_cli"
    elif cmd == "xrd_viewer":
        cmd = "xrdviewer"
    if cmd.startswith("larch "):
        cmd = cmd.replace("larch ", "larch_cli ")

    # compute the desktop file content
    cs = [
        "[Desktop Entry]",
        f"Name={app_name}",
        "Type=Application",
        f"Comment={app_name}",
        f'Terminal={"true" if terminal else "false"}',
        f"Icon=/usr/lib/python3/dist-packages/larch/icons/{icon}.ico",
        f"Exec=/usr/bin/{cmd}",
        f"Categories={';'.join(categories)}",
    ]

    with open(filename, mode="w+") as f:
        f.write("\n".join(cs))
