#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Queue import Queue # for threadsafe work queue
from threading import Thread
import os
import re
import urllib, urllib2

NUMTHREADS = 8  #threads share the work

listing = []
for item in os.listdir('.'):
	try:
		int(item) #fails if nonnumeric
		listing.append(int(item))
	except ValueError, e:
		pass # ignore nonnumeric

listing.sort() #so 100 is last not first


#Create and populate queue
workqueue = Queue()
for directory in listing:
	workqueue.put(directory)
   
def rundeploy(workqueue):
	while True:
		directory = workqueue.get()
		os.system( "cp src.zip " + str(directory) + "/ 2>&1" );
		if 0 == os.system( "cd " +str(directory)+ "; ./deploy_ios.php 2>&1;" ):
			print( "did "+str(directory) )
		else:
			print( "----------------------------------ERROR ON " + str(directory) + "! --------------------------------------------" )
		#os.system cd has no effect on the original python's os.getcwd()
		workqueue.task_done()

print( "Downloading fresh copy of src.zip..." )
urllib.urlretrieve( 'https://appserve.sharefaith.com/appPackage.php?i=src', 'src.zip' )

# IO Threading is really easy in Python:
# see https://docs.python.org/2/library/queue.html
for i in range( NUMTHREADS ):
	worker = Thread(target=rundeploy, args=(workqueue, ) )
	worker.setDaemon(True)
	worker.start()

workqueue.join() #wait til work is done
print 'done!'

#Sanity check some stuff
for num in listing:
	hexdir = ""
	for folder in os.listdir( str(num) ):
		match = re.match('([a-f0-9]+)', folder)
		if match and len(match.group(0)) == 12:
			hexdir = folder
	
	if len(hexdir) != 12:
		print( "Validation failed for " + folder )
		
	titleAndId = os.path.join( str(num), hexdir, 'title_and_id.txt' )
	if not os.path.exists( titleAndId ):
		print( "No title-and-id for " + str(num) )
	else:
		with open( titleAndId, 'r') as checkfile:
			if len(checkfile.read()) < 45:
				print( "Short title-and-id for " + str(num) )
			
