pssh -I tee /tmp/postprep.py <<EOF
#!/usr/bin/env python
COMPOSE_VERSION = "1.6.0"
MACHINE_VERSION = "0.6.0"
SWARM_VERSION = "1.1.0"

import os
import sys
import urllib

clustersize = 5

myaddr = urllib.urlopen("http://myip.enix.org/REMOTE_ADDR").read()

addresses = list(l.strip() for l in sys.stdin)

def makenames(addrs):
    return [ "node%s"%(i+1) for i in range(len(addrs)) ]

while addresses:
    cluster = addresses[:clustersize]
    addresses = addresses[clustersize:]
    if myaddr not in cluster:
        continue
    names = makenames(cluster)
    for ipaddr, name in zip(cluster, names):
        os.system("grep ^%s /etc/hosts || echo %s %s | sudo tee -a /etc/hosts"
                  %(ipaddr, ipaddr, name))
    if myaddr == cluster[0]:
        os.system("[ -f .ssh/id_rsa ] || ssh-keygen -t rsa -f .ssh/id_rsa -P ''")

os.system("sudo apt-get remove -y --purge dnsmasq-base")
os.system("sudo apt-get -qy install python-setuptools pssh apache2-utils httping htop unzip")
os.system("sudo easy_install pip")
os.system("sudo pip uninstall -y docker-compose")
#os.system("sudo pip install docker-compose=={}".format(COMPOSE_VERSION))
os.system("sudo curl -sSL -o /usr/local/bin/docker-compose https://github.com/docker/compose/releases/download/{}/docker-compose-$(uname -s)-$(uname -m)".format(COMPOSE_VERSION))
os.system("sudo chmod +x /usr/local/bin/docker-compose")
os.system("docker pull swarm:{}".format(SWARM_VERSION))
os.system("docker tag -f swarm:{} swarm".format(SWARM_VERSION))
#os.system("sudo curl -sSL https://github.com/docker/machine/releases/download/v{}/docker-machine_linux-amd64.zip -o /tmp/docker-machine.zip".format(MACHINE_VERSION))
#os.system("cd /usr/local/bin ; sudo unzip /tmp/docker-machine.zip")
os.system("sudo curl -sSL -o /usr/local/bin/docker-machine https://github.com/docker/machine/releases/download/v{}/docker-machine-$(uname -s)-$(uname -m)".format(MACHINE_VERSION))
os.system("sudo chmod +x /usr/local/bin/docker-machine*")
os.system("echo 1000000 | sudo tee /proc/sys/net/nf_conntrack_max")
#os.system("""sudo sed -i 's,^DOCKER_OPTS=.*,DOCKER_OPTS="-H unix:///var/run/docker.sock -H tcp://0.0.0.0:55555",' /etc/default/docker""")
#os.system("sudo service docker restart")
EOF
pssh -t 300 -I "python /tmp/postprep.py >>/tmp/pp.out 2>>/tmp/pp.err" < ips.txt
pssh "[ -f .ssh/id_rsa ] || scp -o StrictHostKeyChecking=no node1:.ssh/id_rsa* .ssh"
pssh "grep docker@ .ssh/authorized_keys || cat .ssh/id_rsa.pub >> .ssh/authorized_keys"
