#! /usr/bin/python
import time
import threading
import sys
from subprocess import call, check_output
from random import randint

# Configs Client
ip = "192.168.152.140"
timeWaiting = 20                #seconds
clientSec = int(sys.argv[1])    #seconds
reportTime = 1                  #seconds

# Script
numThreads = [0,1]  #[0]: numThreads | [1]: Flag On(1)/Off(0)
lock = threading.RLock()

def client(num):
    global ip
    call(["wget",ip,"-a","output.txt","-O","files/file_"+str(time.time())])
    update(num,-1)
    return

def update(num,value):
    lock.acquire()
    try:
        num[0]+=value
    finally:
        lock.release()

def manageClients(cliSec, numT):
    for j in range(20):
        for i in range(cliSec):
            t = threading.Thread(target=client, args=(numT,))
            t.start()
            update(numT,1)
            time.sleep(1.0/cliSec)
    numT[1] = 0

def reporter(numT, rr):
    outFileT = open("resultThreads_"+str(clientSec)+".csv", "w")
    outFileD = open("resultData_"+str(clientSec)+".csv", "w")
    outFileT.write("Time,Threads\n")
    outFileD.write("Time,Data\n")
    count = 1
    while numT[1] == 1 or numT[0] > 0:
        time.sleep(rr)
        out = check_output(['du','-h',"-k",'files']).split("\t")
        printInfo(out[0],numT[0])
        outFileT.write(str(count) + "," + str(numT[0]) + "\n")
        outFileD.write(str(count) + "," + str(out[0]) + "\n")
        count += 1

def printInfo(data, num):
    print "========================"
    print ">Data:\t" + data + " KB"
    print ">N. Threads:\t%s" % num
    print "========================"

# Main
manager = threading.Thread(target=manageClients, args=(clientSec,numThreads,))
report  = threading.Thread(target=reporter, args=(numThreads,reportTime,))
manager.start()
report.start()
