#!/usr/bin/env python 

import sys
import warnings
warnings.simplefilter("ignore") # Importing paramiko displays the following warning:
#/home/panstarrs/schastel/local/lib/python2.5/site-packages/pycrypto-2.5-py2.5-linux-x86_64.egg/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.
#  _warn("Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)
import paramiko
warnings.simplefilter("always")
import datetime

def process_arguments(argv):
    if len(argv) == 1:
        usage()
        sys.exit(1)
    elif argv[1] == 'all':
        nodesFilename = '/home/panstarrs/schastel/local/share/ippMhpccStorageNodes'
        nodesFile = open(nodesFilename)
        nodes = []
        for line in nodesFile:
            nodes.append(line[:-1] + ".0")
    elif argv[1] == 'set0':
        nodes = [ "ipp004.0", "ipp005.0", "ipp006.0", "ipp007.0", "ipp008.0", "ipp009.0", 
                  "ipp060.0", "ipp061.0", "ipp062.0", "ipp063.0", "ipp064.0", "ipp065.0", "ipp066.0", ]
    elif argv[1] == 'set1':
        nodes = [ "ipp010.0", "ipp011.0", "ipp012.0", "ipp013.0", "ipp014.0", 
                  "ipp015.0", "ipp016.0", "ipp017.0", "ipp018.0", "ipp019.0", ]
    elif argv[1] == 'set2':
        nodes = [ "ipp020.0", "ipp021.0", "ipp023.0", "ipp024.0", 
                  "ipp025.0", "ipp026.0", "ipp027.0", "ipp028.0", "ipp029.0", ]
    elif argv[1] == 'set3':
        nodes = [ "ipp030.0", "ipp031.0", "ipp032.0", "ipp033.0", "ipp034.0", 
                  "ipp035.0", "ipp036.0", "ipp037.0", "ipp038.0", "ipp039.0", ]
    elif argv[1] == 'set4':
        nodes = [ "ipp040.0", "ipp041.0", "ipp042.0", "ipp043.0", "ipp044.0", 
                  "ipp045.0", "ipp046.0", "ipp047.0", "ipp048.0", "ipp049.0", ]
    elif argv[1] == 'set5':
        nodes = [ "ipp050.0", "ipp051.0", "ipp052.0", "ipp053.0", "ipp054.0", 
                  "ipp055.0", "ipp056.0", "ipp057.0", "ipp058.0", "ipp059.0", ]
    else:
        nodes = []
        for node in argv[1:]:
            nodes.append(node + ".0")
    return nodes

def get_seconds_since_last_message(ssh, node):
    logfilename = '/export/%s/schastel/logs/%s_refresh.log' % (node, node)
    stdin, stdout, stderr = ssh.exec_command('tail -n 1 %s' % (logfilename))
    for line in stdout:
        try:
            last_message_date = datetime.datetime.strptime(line[:-1].split(' ')[0], '%Y-%m-%dT%H:%M:%S')
        except ValueError:
            return 999999
    now = datetime.datetime.now()
    try:
        td = now - last_message_date
    except UnboundLocalError: #local variable 'last_message_date' migh tbe referenced before assignment
        return 999999
    return td.seconds + td.days * 24 * 3600

def get_crontab_status(ssh):
    stdin, stdout, stderr = ssh.exec_command('crontab -l | grep refresh_host.sh')
    crontab_installed = False
    next_run = None
    for line in stdout:
        crontab_installed = True
        if 'nice' not in line:
            print 'In crontab but NOT nice'
        schedule = line.split(' ')
        next_run = schedule[1] + ':' + schedule[0]
    return (crontab_installed, next_run)

def guess_if_update_or_refresh_is_running(ssh):
    stdin, stdout, stderr = ssh.exec_command('ps waux | grep update_host_undefined.sh | grep -v grep')
    update_is_running = False
    for line in stdout:
        update_is_running = True
    stdin, stdout, stderr = ssh.exec_command('ps waux | grep refresh_table.py | grep -v grep')
    refresh_is_running = False
    for line in stdout:
        refresh_is_running = True
    if update_is_running:
        if refresh_is_running:
            message = "Both Update and Refresh are running"
        else:
            message = "Update is running"
    else:
        if refresh_is_running:
            message = "Refresh is running"
        else:
            message = "Nothing is running"
    return message

if __name__ == '__main__':
    nodes = process_arguments(sys.argv)
    show_crontab = False
    for node in nodes:
        node_name = node.split('.')[0]
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(node_name)
        seconds_since_last_message = get_seconds_since_last_message(ssh, node)
        (is_crontab_installed, next_run) = get_crontab_status(ssh)
        print '%s: %s' % (node, guess_if_update_or_refresh_is_running(ssh))
    #     if seconds_since_last_message > 1000 and not is_crontab_installed:
    #         print 'Node %s: Not installed in crontab and last run was %d seconds ago' % (node, seconds_since_last_message)
    #     else:
    #         if is_crontab_installed:
    #             if seconds_since_last_message < 1000:
    #                 msg = "OK"
    #             else:
    #                 msg = "Stopped or crashed? (next run at %s)" % next_run
    #         else:
    #             msg= "Running (but crontab is not installed)"
    #             show_crontab = True
    #         print 'Node %s: %s' % (node, msg)
    # if show_crontab:
    #     print '58 13 * * * /usr/bin/nice -n 19 /home/panstarrs/schastel/dev/FilesMonitoring/refresh_host.sh'
