#! /usr/bin/env python

import commands, os, sys, subprocess


def system(cmd, dry_run=False):
    print "====> Running", cmd
    if dry_run:
        return

    popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    nl = True
    while 1:
        char = popen.stdout.read(1)
        if not char:
            break
        if nl:
            sys.stdout.write("    ")
        sys.stdout.write(char)
        sys.stdout.flush()
        nl = char == "\n"

    st = popen.wait()
    if st != 0:
        sys.exit("Error: command %r failed" % cmd)
    print


def main():
    dry_run = "dry" in os.environ
    st, tags = commands.getstatusoutput("git tag")
    assert st == 0, "failed to get tags"
    tags = set(tags.split())
    import setup
    version = setup.get_version()

    assert version not in tags, "already have tagged %s" % version

    print "building version", version
    st, descr = commands.getstatusoutput("git describe --all --dirty")
    assert st == 0
    dirty = "-dirty" in descr
    if dirty:
        print "working directory is dirty"

    system("tox")
    if not dirty:
        system("git tag %s" % version)
        system("%s setup.py sdist recompress" % sys.executable)
        system("%s setup.py register" % sys.executable, dry_run)
        system("%s setup.py sdist recompress upload" % sys.executable, dry_run)
    else:
        print "WARNING: build was dirty. did not upload or tag a release"
        sys.exit(1)

if __name__ == "__main__":
    main()
