#!/usr/bin/python3

import os
import re
import git
from pathlib import Path


def main():
    main_branch='master'
    
    cwd=Path(os.path.abspath(__file__)).parents[0]
    repo=git.Repo(cwd)
    repo.git.fetch('origin', '+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*')
    
    orig_tag=next((tag for tag in repo.tags if tag.commit == repo.head.commit), None)
    if orig_tag is None:
        raise Exception(f"no tag on current commit {repo.head.commit}")
    
    release_tag=re.search('^(\d+.\d+.\d+)-.*',orig_tag.name)
    if release_tag is None or release_tag[1] is None:
        raise Exception(f"release_tag is None. Error")
    
    print(f'release candidate tag name is {orig_tag.name}')
    print(f'release tag name is {release_tag[1]}')
    
    repo.git.checkout(main_branch)
    repo.git.merge('--no-ff','-X','theirs','-m',f'"release {release_tag[1]}"',orig_tag.name)
    repo.create_tag(release_tag[1],ref='HEAD', message=f'release {release_tag[1]}')
    repo.git.push()
    repo.git.push('--tags')
    #git logf --first-parent master -n 2
    
    print('finished successfully', flush=True)

if __name__ == '__main__':
    main()