#!/usr/bin/python
import os
import subprocess
import signal
import time
import random

names = """Nervous_Energy
Prosthetic_Conscience
Determinist
Irregular_Apocalypse
No_More_Mr_Nice_Guy
Profit_Margin
Revisionist
Trade_Surplus
The_Ends_Of_Invention
Clear_Air_Turbulence
Flexible_Demeanour
Just_Read_The_Instructions
Of_Course_I_Still_Love_You
Limiting_Factor
Cargo_Cult
Little_Rascal
So_Much_For_Subtlety
Unfortunate_Conflict_Of_Evidence
Just_Testing
Very_Little_Gravitas_Indeed
What_Are_The_Civilian_Applications?
Congenital_Optimist
Size_Isn't_Everything
Sweet_and_Full_of_Grace
Different_Tan
Fate_Amenable_To_Change
It's_Character_Forming
Jaundiced_Outlook
Problem_Child
Reasonable_Excuse
Recent_Convert
Tactical_Grace
Unacceptable_Behaviour
Steely_Glint
Highpoint
Shoot_Them_Later
Attitude_Adjuster
Killing_Time
Heavy_Messing
Frank_Exchange_Of_Views
Death_and_Gravity
Ethics_Gradient
Honest_Mistake
Limnivorous
No_Fixed_Abode
Quietly_Confident
Uninvited_Guest
Use_Psychology
What_Is_The_Answer_and_Why?
Wisdom_Like_Silence
Yawning_Angel
Zero_Gravitas
Misophist
Serious_Callers_Only
Not_Invented_Here
Charitable_View
I_Blame_My_Mother
I_Blame_Your_Mother
Just_Passing_Through
Appeal_To_Reason
Break_Even
Long_View
Peace_Makes_Plenty
Sober_Counsel
Within_Reason
Kiss_the_Blade
Frightspear
Furious_Purpose
Riptalon
Xenoclast
Bad_for_Business
Arbitrary
Cantankerous
Only_Slightly_Bent
I_Thought_He_Was_With_You
Space_Monster
A_Series_Of_Unlikely_Explanations
Never_Talk_To_Strangers
Funny,_It_Worked_Last_Time...
Don't_Try_This_At_Home
Eight_Rounds_Rapid
Lightly_Seared_On_The_Reality_Grill
Now_We_Try_It_My_Way
Liveware_Problem
Pure_Big_Mad_Boat_Man
Qualifier
Seed_Drill
Subtle_Shift_In_Emphasis
Transient_Atmospheric_Phenomenon
You_Naughty_Monsters
You'll_Clean_That_Up_Before_You_Leave
Sense_Amid_Madness,_Wit_Amidst_Folly
Me,_I'm_Counting
Total_Internal_Reflection
Armchair_Traveller
Hidden_Income
Hylozoist
No_One_Knows_What_The_Dead_Think
Pelagian
Fixed_Grin
Scar_Glamour
Labtebricolephile
Dressed_Up_To_Party
Ucalegon
Messenger_Of_Truth
Fractious_Person
Rubric_Of_Ruin
Abundance_Of_Onslaught
Vision_Of_Hope_Surpassed
Partial_Photic_Boundary""".splitlines()


def usage():
    print os.sys.argv[0], "p N"
    print "Where p is the port you want the cluster to use and  N is the number of machines you want in the cluster"

if len(os.sys.argv) < 3:
    usage()
    exit(1)

port = int(os.sys.argv[1])
n_machines = int(os.sys.argv[2])
if n_machines < 1:
    usage()
    exit(1)
else:
    kids = []
    machine_names = random.sample(names, n_machines-1)
    machine_names.append(machine_names[0])
    hostname = socket.gethostname()
    for i, machine_name in enumerate(machine_names):
        # cleanup the directory
        directory = "cluster_directory_%d" % i
        os.system("rm -rf " + directory)
        if (i == 0):
            cl = ["../build/debug/rethinkdb", str(port), "--directory", directory, "--machine-name", machine_name, "--port-offset", str(i+port), "--bind", "all"]
        else:
            cl = ["../build/debug/rethinkdb", str(port+i), "--directory", directory, "--machine-name", machine_name, "--join", "%s:%d" % (hostname, 29015 + port), "--port-offset", str(i+port), "--bind", "all"]
        print ' '.join(cl)
        kids += [subprocess.Popen(cl)]
        time.sleep(1)

    time.sleep(1)
    print "CTRL-C to kill me http requests can be sent to ports:",
    for i in range(n_machines):
        if i != 0: 
            print ",",

        print port + (i * 2) + 1,

    print ""

    import sys
    sys.stdout.flush()

    try:
        signal.pause()
    except:
        for kid in kids:
            kid.terminate()
