#!/usr/bin/python3
#
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 tw=100 et ai si
#
# Copyright (C) 2020-2022 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
# Authors: Juha Haapakorpi <juha.haapakorpi@linux.intel.com>
#          Artem Bityutskiy <artem.bityutskiy@linux.intel.com>

"""Convert CHANGELOG.md to Debian changelog."""

import re
import sys
import argparse
from pathlib import Path
from datetime import datetime
import _Changelogmd

try:
    import argcomplete
except ImportError:
    # We can live without argcomplete, we only lose tab completions.
    argcomplete = None

VERSION = "1.0.0"
OWN_NAME = "changelog_md_to_debian"

def parse_arguments():
    """Parse input arguments."""

    text = sys.modules[__name__].__doc__
    parser = argparse.ArgumentParser(description=text, prog=OWN_NAME)

    text = "Print version and exit."
    parser.add_argument("--version", action="version", help=text, version=VERSION)

    text = """The output file path."""
    arg = parser.add_argument("-o", "--outfile", metavar="PATH", type=Path, help=text)
    if argcomplete:
        arg.completer = argcomplete.completers.FilesCompleter()

    text = """Name of the project."""
    parser.add_argument("-p", "--project-name", metavar="PRGNAME", default="prjname", help=text)

    text = """Full name of the project maintainer."""
    parser.add_argument("-n", "--maintainer-name", metavar="NAME", default="Boo Hoo", help=text)

    text = """Email address of the project maintainer."""
    parser.add_argument("-e", "--maintainer-email", metavar="EMAIL",
                        default="boo.hoo@company.com", help=text)

    text = """The input CHANGELOG.md file in a format described here:
              https://keepachangelog.com/en/1.0.0"""
    arg = parser.add_argument("infile", metavar="PATH", type=Path, help=text)
    if argcomplete:
        arg.completer = argcomplete.completers.FilesCompleter()

    if argcomplete:
        argcomplete.autocomplete(parser)

    return parser.parse_args()

def handle_entry(args, entry):
    """Convert CHANGELOG.md entries to Debian changelog format."""

    lines = entry.splitlines()

    # Example of start of a entry line we are matching: "## [1.8.11] - 2021-01-13".
    mobj = re.match(r"^## \[(\d+.\d+.\d+)]\s+-\s+(\d+-\d+-\d+)", lines[0])
    if not mobj:
        if "ADD DATE HERE" in lines[0]:
            return ""
        raise ValueError(f"bad first line of a changelog entry:\n{lines[0]}")

    version, date = mobj.groups()

    # Convert the date to the Debian changelog format.
    datetimeobj = datetime.strptime(date, "%Y-%m-%d")
    date = f"{datetimeobj.strftime('%a, %d %b %Y %H:%M:%S')} +0200"

    substitutions = [
        (r"\s+-\s+", "  * "),
        (r"\s\s\s+", "    "),
    ]

    changes = []
    for line in lines[1:]:
        if line.startswith("#"):
            continue

        for old, new in substitutions:
            line = re.sub(old, new, line)

        changes.append(line)

    changes = "\n".join(changes)

    return (f"{args.project_name} ({version}) unstable; urgency=low\n\n"
            f"{changes}\n\n -- {args.maintainer_name} <{args.maintainer_email}>"
            f"  {date}\n\n")

def changelog_md_to_debian(args):
    """Convert CHANGELOG.md to Debian changelog."""

    outtext = ""
    for entry in _Changelogmd.get_chmd_entries(args.infile):
        outtext += handle_entry(args, entry)

    outtext = outtext.strip()
    if args.outfile:
        with open(args.outfile, "w", encoding='utf-8') as fobj:
            fobj.write(outtext)
    else:
        print(outtext)

def main():
    """Script entry point."""

    args = parse_arguments()

    args.maintainer_name = " ".join([part.strip() for part in args.maintainer_name.split()])

    changelog_md_to_debian(args)

    return 0

if __name__ == "__main__":
    sys.exit(main())
