#!/usr/bin/env python


import sys
import click
import subprocess


def runcmd(*args):
    print(*args)
    return 0


def runscript(run, *script):
    for cmd in script:
        click.echo(cmd)
        retcode = run(cmd)
        if retcode != 0:
            sys.exit(retcode)


def parseVersion(version):
    if version.startswith('v'):
        version = version[1:]
    verparts = [int(x) for x in version.split('.')]
    return verparts


def checkVersion(old, new):
    ovp = parseVersion(old)
    nvp = parseVersion(new)
    if ovp[0] > nvp[0]:
        return 'version must increase'
    elif ovp[0] == nvp[0]:
        if ovp[1] > nvp[1]:
            return 'version must increase'
        elif ovp[1] == nvp[1]:
            if ovp[2] > nvp[2]:
                return 'version must increase'
            return
        else:
            if nvp[2] > 0:
                return 'patch level must be zero if minor version increases'
    else:
        if nvp[1] > 0:
            return 'minor version must be zero if major version increases'


@click.command()
# ,help='the name of the release')
@click.option('--dryrun', '-n', is_flag=True, default=False)
@click.argument('version', default='')
def main(dryrun, version):
    if dryrun:
        run = runcmd
    else:
        run = subprocess.call

    with open('VERSION', 'rt') as fi:
        oldv = fi.read().strip()
    if version == '':
        click.echo('current version: ' + oldv)
        sys.exit(1)
    if oldv == version:
        click.echo('version number not changed')
        sys.exit(2)

    msg = checkVersion(oldv, version)
    if msg:
        click.echo(msg)
        sys.exit(3)

    if dryrun:
        click.echo(['echo', '-n', version, '>VERSION'])
    else:
        with open('VERSION', 'wt') as fo:
            fo.write(version)

    runscript(run,
              ['git', 'add', 'VERSION'],
              ['git', 'commit', '-m', 'bump version number: v' + version],
              ['git', 'tag', '-a', 'v' + version, '-m', 'v' + version],
              ['git', 'push', 'origin'],
              ['git', 'push', 'origin', '--tags'],
              [sys.executable, 'setup.py', 'sdist', 'upload'],
              )

if __name__ == '__main__':
    main()
