#!/usr/bin/env python

HOME = '/home/panstarrs/schastel'
REFRESH_SCRIPT_LOCATION = '%s/dev/FilesMonitoring/NodeRelated/refresh_table.py' % HOME
ROOT_DIRECTORY = '%s/dev/FilesMonitoring/NodeRelated/deployment' % HOME
PYTHONPATH = '%s/local/share/python' % HOME
NODES_LIST = '%s/local/share/allStorageNodes' % HOME
OUTPUT_DIRECTORY = '%s/scripts' % ROOT_DIRECTORY
DEPLOYMENT_SCRIPT = '%s/deploy.sh' % OUTPUT_DIRECTORY
NODE_SCRIPT_FORMAT = '%s/crontab.%%s' % OUTPUT_DIRECTORY

if __name__ == '__main__':
    nodes_file = open(NODES_LIST)
    deployment_script_file = open(DEPLOYMENT_SCRIPT, 'w')
    deployment_script_file.write('#!/bin/bash\n\n')
    minutes = 1
    hours = 0
    for node in nodes_file:
        node = node[:-1]
        print '... Generating script for %s' % node
        crontab_filename = NODE_SCRIPT_FORMAT % node
        deployment_script_file.write("echo '%s'\n" % (node))
        deployment_script_file.write("ssh %s 'crontab %s'\n" % (node, crontab_filename))
        crontab_file = open(crontab_filename, 'w')
        crontab_file.write("MAILTO=schastel@ifa.hawaii.edu\n")
        crontab_file.write("PYTHONPATH=%s\n" % PYTHONPATH)
        crontab_file.write("%d %d * * * nice %s -disk 0\n" % (minutes, hours, REFRESH_SCRIPT_LOCATION))
        if not node.startswith('ipp'): #atrc or stsci nodes: add disks 1 and 2
            crontab_file.write("%d %d * * * nice %s -disk 1\n" % ((minutes+1)%60, hours, REFRESH_SCRIPT_LOCATION))
            crontab_file.write("%d %d * * * nice %s -disk 2\n" % ((minutes+2)%60, hours, REFRESH_SCRIPT_LOCATION))
        minutes += 7
        minutes %= 60
	hours += 1
	hours %= 24
        crontab_file.close()
    nodes_file.close()
    deployment_script_file.close()
    print '\nNow run: %s\n' % DEPLOYMENT_SCRIPT

