#!/usr/bin/python


"""
	This script launch all the download workers that are configured in the
	settings module.

	You must set the enviroment variable PYTHONPATH to the directory containing
	the petra folder.
"""


import threading
from django.conf import settings

import time

import os

os.environ["DJANGO_SETTINGS_MODULE"] = "petra.settings"

try:
	import settings # Assumed to be in the same directory.
	from petra.rsdownloads.models import *
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\nTry to define PYTHONPATH variable to the directory containing petra_daemon.py.\n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
	print "Initializing daemon"

	print "Cleaning unfinished downloads"

	downloads = Download.objects.filter(status=1)
	for download in downloads:
		download.status = 0
		download.save()

	print "Creating mutex lock"
	lock = threading.BoundedSemaphore(1)

	print "Creating %d download workers" % settings.MAX_WORKERS
	workers = list()
	for i in range(settings.MAX_WORKERS):
		worker_name = "Worker_%d" % i
		worker = DownloadWorker(lock, worker_name)
		worker.start()
		workers.append(worker)
	
	try:
		while True:
			time.sleep(30)
	except KeyboardInterrupt:
		print "Sending all workers the kill signal ..."
		sys.exit(1)
