#! /usr/bin/python3

'''Tag a git repository.
'''

import argparse
import os
import subprocess
import sys


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--force', action='store_true')
    parser.add_argument('-m', '--message', dest='message', type=str)
    parser.add_argument('-b', '--browser', action='store_true')
    args = parser.parse_args()
    return args


def main():
    args = parse_args()

    # determine main branch
    for name in ('main', 'master'):
        remote_branch = 'origin/' + name
        try:
            subprocess.check_call(['git', 'rev-parse', remote_branch],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except subprocess.CalledProcessError:
            continue
        else:
            break
    else:
        print('no remote branch?')
        sys.exit(0)

    current_version = subprocess.check_output(['git', 'describe', remote_branch]).decode('ascii')
    if '-g' not in current_version and not args.force:
        print('nothing to do')
        sys.exit(0)

    version_parts = [int(x) for x in current_version.strip('v').split('-')[0].split('.')]
    version_parts[-1] += 1
    if len(version_parts) > 1 and version_parts[-1] >= 100:
        version_parts[-2] += 1
        version_parts[-1] = 0
    new_tag_value = 'v' + '.'.join([str(x) for x in version_parts])
    #subprocess.call(['git', 'log', '--oneline', '%s..%s' % (current_version.split('-')[0], remote_branch)])
    while True:
        ok = input('tag with %s, ok? [Y/n/o/l] ' % new_tag_value)
        if ok.lower() == 'o':
            while True:
                new_tag_value = input('enter tag: ').strip()
                if new_tag_value.startswith('v'):
                    break
            continue
        if ok.lower() == 'l':
            # log
            continue
        if ok.lower() == 'n':
            print('aborting')
            sys.exit(0)
        break
    message = args.message or new_tag_value
    subprocess.check_call(['git', 'tag', '-a', new_tag_value, remote_branch, '-m', message])
    subprocess.check_call(['git', 'push', 'origin', new_tag_value])
    if args.browser:
        module_name = os.getcwd().split('/')[-1]
        jenkins_names = {}  # mapping for jenkins jobs != git module names
        module_name = jenkins_names.get(module_name, module_name)
        if module_name in ('publik-base-theme', 'combo-plugin-gnm', 'godo'):
            # full build
            subprocess.check_call(['sensible-browser',
                'https://jenkins.entrouvert.org/job/gitea/job/%s/job/main/' % module_name])
        else:
            # restart at last step
            subprocess.check_call(['sensible-browser',
                'https://jenkins.entrouvert.org/job/gitea/job/%s/job/main/lastBuild/restart/' % module_name])


if __name__ == '__main__':
    main()
