#!/usr/bin/env python
import os, sys, re
from random import choice
import socket
import threading
import random
import time


def exec_cmd( cmd ):
    child = os.popen( cmd )
    output = child.readlines()
    err = child.close()
    if err:
        raise RuntimeError, "%r failed with exit code %d" % (cmd, err)
    return output

    
class WorkerThread(threading.Thread):
	"""
	Do the actual work
	"""
	def __init__(self, mutex, ip, command):
		self.mutex = mutex
		self.ip = ip
		self.command = command
		threading.Thread.__init__(self)
        
	def run(self):
		delay = random.randint(1,10)
		self.mutex.acquire()
		print "Random Delay for %d seconds" % (delay)
		self.mutex.release()
		time.sleep(delay)

		self.mutex.acquire()
		print "Executing %s on %s" % (self.command, self.ip)
		self.mutex.release()

		# Log what happens
		self.fp = open( "%s.log" % (self.ip), "a" )

		# Check for previous deploys
		ssh_cmd = 'ssh %s "%s"' % (self.ip, self.command)
		result = exec_cmd( ssh_cmd )
		self.fp.write("%s\n" % (ssh_cmd))
		self.fp.write("%s\n" % (result))
		self.fp.close()

		self.mutex.acquire()
		print "Execution is Finished for %s" % (self.ip)
		self.mutex.release()


if __name__ == '__main__':
	targets = ['box-1.home', 'box-2.home', 'box-3.home', ]
	targets = ['bcl@neil.home', 'root@fozzy.home', 'etelos@lister.home', ]
	command = "id"

	# Launch a thread for each target
	stdoutmutex = threading.Lock()
	threads = []
	for ip in targets:
		thread = WorkerThread(stdoutmutex,ip,command)
		thread.start()
		threads.append(thread)
   
	for thread in threads:
		thread.join()
