#! {{sys_executable}}
########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
############

import re
import subprocess

CURRENT_BRANCH_CMD = 'git symbolic-ref --short HEAD'
TAG_CMD = 'git tag -f {0}'
PUSH_TAG_DELETE_CMD = 'git push origin :{0}'
PUSH_TAG_CREATE_CMD = 'git push origin {0}'

BUILD_BRANCH_REGEX = '(.+)-build'


def _run(cmd, output=False):
    split_cmd = cmd.split(' ')
    try:
        if output:
            return subprocess.check_output(split_cmd).decode('utf-8').strip()
        else:
            subprocess.check_call(split_cmd)
    except BaseException as e:
        raise SystemExit('error: failed running: {0} [{1}]'.format(cmd, e))


def retag():
    branch_name = _run(CURRENT_BRANCH_CMD, output=True)
    match = re.match(BUILD_BRANCH_REGEX, branch_name)
    if match:
        tag = match.group(1)
        _run(TAG_CMD.format(tag))
        _run(PUSH_TAG_DELETE_CMD.format(tag))
        _run(PUSH_TAG_CREATE_CMD.format(tag))
    else:
        raise SystemExit('error: {0} is not a build branch'.format(
            branch_name))


if __name__ == '__main__':
    retag()
