#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import argparse
import subprocess
import sys


def create_output(args):
    last_line = None
    if args.css:
        first = "/*-"
        sep = "+"
        cont = ""
        last = "'"
        end = "*/"
    elif args.cpp:
        first = "// ."
        cont = "// "
        sep = "// +"
        last = "// '"
        end = "'"
    elif args.js:
        first = "//#   ."
        sep = "//#   +"
        cont = "//#   "
        last = "//#   '"
        end = "'"
        last_line = "//#."
    else:
        first = "#   .-"
        sep = "#   +"
        cont = "#   "
        last = "#   '-"
        end = "'"
        last_line = "#."

    width = 76
    sepmid = sep + "-" * (width - len(sep) - 1) + "+"
    title = " ".join(args.title)
    first_line = first + "-" + title

    output = [first_line + "-" * (width - len(first_line) - 1) + "."]
    with subprocess.Popen(
        ["figlet", "-c", "-w", "%s" % (width - 7), title],
        shell=False,
        stdout=subprocess.PIPE,
        encoding="utf-8",
    ) as proc:
        if proc.stdout is None:
            raise Exception("Huh? stdout vanished...")
        for line in proc.stdout:
            output.append((cont + "|%-" + str(width - len(cont) - 2) + "s|") % line[:-1])

    if not args.no_subtitle:
        output.append(sepmid)
        output.append(cont + "|" + " " * (width - len(cont) - 2) + "|")

    output.append(last + "-" * (width - len(last) - len(end)) + end)
    if last_line:
        output.append(last_line)
    return output


def parse_arguments(argv):
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument("--css", action="store_true", help="CSS header")
    parser.add_argument("--cpp", action="store_true", help="C++ header")
    parser.add_argument("--js", action="store_true", help="JS header")
    parser.add_argument("--no-subtitle", action="store_true", help="No subtitle line")
    parser.add_argument("title", nargs="+", help="Title")
    return parser.parse_args(argv)


def main():
    args = parse_arguments(sys.argv[1:])
    output = create_output(args)
    sys.stdout.write("%s\n" % "\n".join(output))


if __name__ == "__main__":
    main()
