#!/usr/bin/env python

import os

bin_directory = "%s/%s/bin" % (os.environ['PSCONFDIR'], os.environ['PSCONFIG'])
share_directory = "%s/%s/share/filemon/" % (os.environ['PSCONFDIR'], os.environ['PSCONFIG'])

REFRESH_SCRIPT_LOCATION = '%s/refresh_table.py' % bin_directory
ROOT_DIRECTORY = '%s/deployment' % share_directory
PYTHONPATH = '%s/python' % share_directory
NODES_LIST = '%s/allStorageNodes' % share_directory
OUTPUT_DIRECTORY = '%s/scripts' % share_directory
DEPLOYMENT_SCRIPT = '%s/deploy.sh' % OUTPUT_DIRECTORY
NODE_SCRIPT_FORMAT = '%s/crontab.%%s' % OUTPUT_DIRECTORY

if __name__ == '__main__':
    nodes_file = open(NODES_LIST)
    if not os.path.exists(OUTPUT_DIRECTORY):
        os.makedirs(OUTPUT_DIRECTORY)
    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("SHELL=/bin/tcsh\n")
        crontab_file.write("MAILTO=%s@ifa.hawaii.edu\n" % os.environ['USER'] )
        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

