#!/usr/bin/python3

# put this in .git/hooks and ensure it has exec permissions: "chmod +x prepare-commit-msg"
# use the following steps to use it globally
# - create ~/.git-templates
# - run the command: "git config --global init.templateDir '~/.git-templates'"
# - reinitialize existing git repos you wish to use this in: "git init"

import re, subprocess, sys

JIRA_ISSUE_URL = "https://smartvending.atlassian.net/browse/"
PREPEND_TICKET = True
APPEND_ISSUE_LINK = True
REGEX = re.compile("^(.*/)?([A-Z]+-[0-9]+)", re.IGNORECASE)


def main():
    commit_file = sys.argv[1]

    git_branch_name = subprocess.run(
        ["git", "branch", "--show-current"],
        stdout=subprocess.PIPE,
        encoding="utf-8",
    )

    match = REGEX.match(git_branch_name.stdout)

    if match:
        try:
            ticket = match.group(2)
        except IndexError:
            return
        ticket_url = f"{JIRA_ISSUE_URL}{ticket}"

        with open(commit_file, "r+") as f:
            contents = f.read().strip()

            if PREPEND_TICKET and not contents.startswith(ticket):
                contents = f"{ticket}: {contents}"

            if APPEND_ISSUE_LINK:
                contents = f"{contents}\n\n{ticket_url}"

            f.seek(0)
            f.write(contents)


if __name__ == "__main__":
    main()
