#! /usr/bin/env python

import sys, os, subprocess, struct, re


def find_executables():
    rx = re.compile("python([23][0-9])(-x64)?", re.I)

    search_path = os.path.dirname(os.path.dirname(sys.executable))
    entries = os.listdir(search_path)
    res = []
    for x in entries:
        m = rx.match(x)
        if not m:
            continue
        exepath = os.path.join(search_path, x, "python.exe")
        if os.path.isfile(exepath):
            res.append((m.group(1), exepath))
    return res


def system(cmd):
    sys.stdout.write("====> Running %s\n" % cmd)

    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)
    sys.stdout.write("\n")


def main():
    upload = ""
    if "upload" in sys.argv:
        upload = "upload"

    for v, x in find_executables():
        for dist in ['bdist_egg', 'bdist_wininst']:
            cmd = "%s setup.py -q %s fixup %s" % (x, dist, upload)
            system(cmd)

if __name__ == "__main__":
    main()
