#!/usr/bin/env python3
# vim: fdm=marker

# A script that generates config files for sxhkd

import argparse, pathlib, re, os, sys

# Data {{{

HEADER = """# vim: ft=conf fdm=marker

# This file is automatically generated.
# To modify things, please modify the files on the ~/.config/sxhkd folder.

"""

CONFIG_HOME = pathlib.Path(
    os.environ["XDG_CONFIG_HOME"] if "XDG_CONFIG_HOME" in os.environ
    else "~/.config"
).expanduser()

# }}}

def main():
    args = create_argparser().parse_args(sys.argv[1:])
    templates_folder = pathlib.Path(
        CONFIG_HOME / "sxhkd" if args.path == None
        else args.path[0]
    )
    output = ""

    if templates_folder.is_dir():
        for template in args.template:
            template_path = templates_folder / template
            if template_path.is_file():
                with template_path.open("r") as f:
                    output += f.read() + "\n"
            else:
                print(f"{template_path} not found. Please create it or remove it from the args.")
                sys.exit(2)
    else:
        print(f"{templates_folder} not found. Please create said directory and store the template files there, or specify another one with the -p option.")
        sys.exit(2)

    double_line = re.compile(r"\n\n")
    while re.findall(double_line, output) != []:
        output = re.sub(double_line, "\n", output)
    output = re.sub(r"(?m)^#.*\n?", "", output)
    output = HEADER + output

    print(output)

def create_argparser():
    p = argparse.ArgumentParser(
        prog = pathlib.Path(sys.argv[0]),
        description = "a script to generate a config file for sxhkd, based on multiple template files."
    )

    p.add_argument(
        "template",
        help="template files to append to the output, located in XDG_CONFIG_HOME/sxhkd/ or ~/.config/sxhkd/",
        action="store",
        type=str,
        nargs="+",
    )

    p.add_argument(
        "-p", "--path",
        help="an alternative path on where to find the style folders",
        action="store",
        type=str,
        nargs=1,
    )

    return p

if __name__ == "__main__":
    main()
