#!/usr/bin/env python
import sys, re
from subprocess import check_output

class bcolors:
    HEADER      = '\033[95m'
    OKBLUE      = '\033[94m'
    OKGREEN     = '\033[92m'
    WARNING     = '\033[93m'
    FAIL        = '\033[91m'
    ENDC        = '\033[0m'
    BOLD        = '\033[1m'
    UNDERLINE   = '\033[4m'

branch_info = 'Branch name must starts with a valid branch type followed by valid JIRA-ID\n\
Types of branch - \n\
    feature:    Adding a new feature\n\
    bugfix:     Fixing a bug\n\
    hotfix:     Hotfix for a release\n\
    Rename branch command: git branch -m "<new-branch-name>"\n\
    ' + bcolors.HEADER + 'eg. => feature/LOFIOS-199-UserAgent' + bcolors.ENDC

commit_msg_info = 'Types of commit - \n\
    feat:       Add a new feature (equivalent to a MINOR in Semantic Versioning).\n\
    fix:        Fix a bug (equivalent to a PATCH in Semantic Versioning).\n\
    docs:       Documentation changes.\n\
    style:      Code style change (semicolon, indentation...).\n\
    refactor:   Refactor code without changing public API.\n\
    perf:       Update code performances.\n\
    test:       Add test to an existing feature.\n\
    chore:      Update something without impacting the user (ex: bump a dependency in package.json).\n\
    ' + bcolors.HEADER + 'eg. => fix(code): Fixed the multithreded issue for consumer.' + bcolors.ENDC

branch_regex = '(feature|bugfix|hotfix)\/(LOFIOS-\d+)'
commit_regex = '^(revert: )?(feat|fix|docs|style|refactor|perf|test|chore)(\(.+\))?: .{1,50}'


commit_msg_filepath = sys.argv[1]
branch = check_output(['git', 'symbolic-ref', '--short', 'HEAD']).strip()

if re.match(branch_regex, branch):
    issue = re.match(branch_regex, branch).group(2)
    with open(commit_msg_filepath, 'r+') as fh:
        commit_msg = fh.read()
        if re.match(commit_regex, commit_msg):
            fh.seek(0, 0)
            fh.write('[%s] %s' % (issue, commit_msg))
        else:
            print bcolors.WARNING + 'Incorrect commit message' + bcolors.ENDC
            print bcolors.FAIL + 'prepare-commit-msg - ' + bcolors.BOLD + 'FAILED' + bcolors.ENDC
            print commit_msg_info
            sys.exit(1)
elif branch != 'master' and branch != 'develop':
    print bcolors.WARNING + 'Incorrect branch name: ' + bcolors.BOLD + '' + branch + bcolors.ENDC
    print bcolors.FAIL + 'prepare-commit-msg - ' + bcolors.BOLD + 'FAILED' + bcolors.ENDC
    print branch_info
    sys.exit(1)
