#!/usr/bin/python
import sys, os

def usage():
    print("foreachdir [--print] command <options>")
    print("foreachdir [--print] dir1 dir2 ... command <options>")

def parse(argv):
    dlist=[]
    index = 0
    for i in argv:
        if os.path.isdir(i):
            dlist.append(i)
            index += 1
        else:
            break
    if (index != 0): # at least expplicitly specify one dir
        cmd = argv[index:]
    else:
        dlist = [i for i in os.listdir(".") if os.path.isdir(i)]
        cmd = argv

    return (dlist,cmd)

if __name__=="__main__":
    if (len(sys.argv)<=1):
        usage()
        sys.exit(0)

    try:
        if (sys.argv[1] == "--print"):
            onlyPrint = True
            argv = sys.argv[2:]
        else:
            onlyPrint = False
            argv = sys.argv[1:]

        (dirlist, command) = parse(argv)
    except IndexError:
        usage()
        sys.exit(1)

#     print (dirlist)
#     print (command)

    for d in dirlist:
        c = "cd "+ d +"; " + " ".join(command) +"; cd .."
        if (onlyPrint):
            print (c)
        else:
            print("== "+ c +" ==")
            os.system(c)


