#!/usr/bin/python

from optparse import OptionParser
from datetime import datetime
import logging
from utils import cluster
from utils import package
from utils import config
from utils import command
import os, errno
import signal
import sys
from isi.misc import sysctlbyname

ISI_PHONE_HOME_LOG_FILE_PATH = '/var/log/isi_phone_home.log'
LOGGING_FILE = '/var/run/phone_home_logging.level'
LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}
CFG = None
cl = None
lf = -1

def getConfig():

    global CFG
    global cl
    global lf
    try:
        CFG = config.Config()
        cl = cluster.Cluster()
        lf = -1
    except:
        exit(1)

def extract_commands(list):

    result = []
    try:
        with open(list, 'r') as list_fd:
            for line in list_fd:
                data = line.split('||')
                if len(data) == 4:
                    result.append({'cmd': data[1], 'node': data[0],'data_file_name': data[2], 'timeout': data[3]})
                else:
                    logging.error("Can't parse the line {0}".format(line))
    except IOError:
        logging.error("Can't open the file")
    except Exception as e:
        logging.error("Error: {0} found while extracting commands".format(str(e)))
    return result

def add_date(file_name):

    try:
        with open(file_name, "a") as f:
            f.write("\n___DATE___\n")
            f.write("\n{0}\n".format(datetime.utcnow().isoformat()))
    except Exception as e:
        logging.error('Error:{0} when adding date to file: {1} '.format(str(e), file_name))

def run_list(list_file_name):

    list_path = os.path.join(CFG.get('LISTDIR'), list_file_name)
    if os.path.isfile(list_path):
        commands = extract_commands(list_path)
        for cmd in commands:
            if cmd.has_key('cmd') and cmd.has_key('data_file_name') and cmd.has_key('timeout') and \
                        cmd.has_key('node'):
                if str(cmd['data_file_name']).find('/') == -1:

                    date_t = datetime.utcnow().strftime("%Y-%m-%d_0000")
                    file_name = "{0}-{1}".format(date_t, cmd['data_file_name'])
                    if cmd['node'].upper() == 'NODE':
                        node = cl.local_node()
                        full_name = os.path.join(CFG.get('DATADIR'),str(node) ,file_name)
                    else:
                        full_name = os.path.join(CFG.get('DATADIR'), file_name)
                    add_date(full_name)
                    cmd_str = '{0} 1>> {1} 2>&1'.format(cmd['cmd'], full_name)

                    cmd_thread = command.Command(cmd_str)
                    exit_code, output = cmd_thread.run(int(cmd['timeout']))
                    if exit_code:
                        logging.error('Command: {0} failed with error code: {1}'.format(output, exit_code))
                else:
                    logging.error('Data file name: {1} contains / which is an invalid character'.format(cmd['data_file_name']))

            else:
                logging.error("Error to parse a line from file: {0}, some values are missing".format(list_file_name))
    else:
        logging.error("File {0} doesn't exist".format(list_file_name))

def  run_script(script_file_name):
    base = CFG.get('SCRIPTDIR')
    script_path = base + '/' + script_file_name
    real_path = os.path.realpath(script_path)

    if os.path.commonprefix((real_path, base)) != base:
        message = "File: {0} doesn't exist or is invalid".format(real_path)
        logging.error(message)
        print(message)
        return

    if os.path.isfile(script_path):
        cmd = 'python ' + script_path  + ' 2>&1 '
        command_thread = command.Command(cmd)
        exit_code, output = command_thread.run(int(CFG.get("SCRIPT_TIEMOUT")))
        if exit_code:
            logging.error("Error: {0} running script: {1} ".format(str(exit_code), output))
    else:
        logging.error("File: {0} list_file_name doesn't exist ".format(script_path))

def send_data():
    try:
        pkg = package.Package()
    except:
        exit(1)
    node = cl.check_connectivity()
    if node:
        pkg.send(node, node == cl.local_node())
    else:
        logging.error("Nodes in this cluster failed to reach an active ESRS gateway")


def create_package():

    try:
        pkg = package.Package()
    except:
        exit(1)
    cluster_name = cl.get_name()
    if pkg.create(cluster_name):
        logging.info('Package created')
    else:
        logging.error('Failed to create the package')


def delete_package():
    try:
        pkg = package.Package()
    except:
        exit(1)

    pkg.delete()



def parseargs():

    parser = OptionParser(usage='usage: %prog [OPTIONS]',
                          description='Tool to collect and send data back to EMC')
    parser.add_option('-o', '--logging-level', dest='logging_level', help='Allow to change the loging level to debug, info, warning, error or critical')
    parser.add_option('-l', '--list-file', dest='list_file', help='Run a list file to collect data')
    parser.add_option('-r', '--script-file', dest='script_file', help='Run a script file to collect data')
    parser.add_option('-s', '--send-data', action='store_true', default=False, dest='send_data',
                      help='Send data package to EMC')
    parser.add_option('-t', '--delete-data', action='store_true', default=False, dest='delete_data',
                      help='Delete packages older than 30 days')
    parser.add_option('-c', '--create-package', action='store_true', default=False, dest='create_package',
                      help='Create data package')
    parser.add_option('-e', '--enable', action='store_true', default=False, dest='enable',
                      help='enable the tool')
    parser.add_option('-d', '--disable', action='store_true', default=False, dest='disable',
                      help='Disable the tool')
    (options, args) = parser.parse_args()
    args_ok = False
    if options.list_file and not (options.disable or options.enable or options.script_file or options.send_data or options.create_package or options.delete_data or options.logging_level):
        args_ok=True
    if options.disable and not (options.list_file or options.enable or options.script_file or options.send_data or options.create_package or options.delete_data or options.logging_level):
        args_ok=True
    if options.enable and not (options.disable or options.list_file or options.script_file or options.send_data or options.create_package or options.delete_data or options.logging_level):
        args_ok=True
    if options.script_file and not (options.disable or options.enable or options.list_file or options.send_data or options.create_package or options.delete_data or options.logging_level):
        args_ok=True
    if options.send_data and not (options.disable or options.enable or options.script_file or options.list_file or options.create_package or options.delete_data or options.logging_level):
        args_ok=True
    if options.create_package and not (options.disable or options.enable or options.script_file or options.list_file or options.send_data or options.delete_data or options.logging_level):
        args_ok=True
    if options.delete_data and not (options.disable or options.enable or options.script_file or options.list_file or options.send_data or options.create_package or options.logging_level):
        args_ok=True
    if options.logging_level and not (options.disable or options.enable or options.script_file or options.list_file or options.send_data or options.create_package or options.delete_data):
        args_ok=True
    if not args_ok:
        msg = 'Invalid option, please use only one of the valid options'
        parser.error(msg)
    return options, args

def phone_home_status():

    phone_home_disable_file = CFG.get('DISABLEFILE')
    phone_home_rootdir = CFG.get('ROOTDIR')
    if not os.path.isfile(phone_home_disable_file) \
            and os.path.isdir(phone_home_rootdir):
        return True
    else:
        return False


def enable_phone_home():

    phone_home_disable_file = CFG.get('DISABLEFILE')
    init_iph()
    try:
        os.remove(phone_home_disable_file)
        logging.info('Tool is enabled')
        print "Phone Home has been enabled successfully"
        sys.stdout.flush()
    except OSError as e:
        if e.errno != errno.ENOENT:
            logging.error('Failed to delete file {0}'.format(phone_home_disable_file))
        else:
            print "Phone Home has been enabled successfully"
            sys.stdout.flush()


def disable_phone_home():

    phone_home_status_file = CFG.get('DISABLEFILE')
    if not os.path.isfile(phone_home_status_file):
        try:
            with open(phone_home_status_file, 'w') as f:
                f.write('disabled')
            logging.info('Tool is disabled')
            print "Phone Home has been disabled successfully"
            sys.stdout.flush()
        except:
            logging.error('Failed to update status file: {0}'.format(phone_home_status_file))
            exit(1)

def node_subdirs():
    nodes = cl.list_nodes()
    for node in nodes:
        node_path = os.path.join(CFG.get('DATADIR'), str(node))
        if not os.path.exists(node_path):
            os.makedirs(node_path)

def change_logging(level_name):

    f = None


    if len(level_name) > 1:
        level = LEVELS.get(str(level_name).lower())
        if level is not None:
            try:
                file = LOGGING_FILE
                f = os.open(file, os.O_RDWR|os.O_CREAT|os.O_EXLOCK|os.O_TRUNC, 0600)
                os.write(f, '{0}'.format(str(level)))
                os.close(f)
                print "Logging level has been changed successfully"
                sys.stdout.flush()
            except Exception as e:
                print "Error {0}".format(str(e))

        else:
            print "Please introduce a valid logging value: debug, info, warning, error or critical"
            sys.stdout.flush()
    else:
        print "Please introduce a valid logging value: debug, info, warning, error or critical"
        sys.stdout.flush()

def get_logging_level():

    try:
        file = LOGGING_FILE
        with open(file) as f:
            level = int(f.readline())
            return level
    except:
        return logging.ERROR

def init_iph():
    if not os.path.exists(CFG.get('DATADIR')):
        os.makedirs(CFG.get('DATADIR') + '/')
    if not os.path.exists(CFG.get('PKGDIR')):
        os.makedirs(CFG.get('PKGDIR'))
    node_subdirs()
    if not os.path.isfile(LOGGING_FILE):
        change_logging('error')

def check_rights():
    if cl.is_compliance() and  os.getuid() > 0:
        logging.error("Permission denied")
        print "Permission denied"
        exit(1)

def hasQuorum():
    return bool(int(sysctlbyname("efs.gmp.has_quorum")))

def main():
    options, args = parseargs()
    if hasQuorum():
        getConfig()
        check_rights()
        new_level = get_logging_level()
        try:
            logging.basicConfig(format='[%(asctime)s] p%(process)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p', filename=ISI_PHONE_HOME_LOG_FILE_PATH,level=new_level)
        except Exception as e:
            print e
        # Bug 218321
        # Allow phone home to be enabled without ESRS enabled.
        if options.enable:
            enable_phone_home()

        if options.disable:
            disable_phone_home()

        if options.logging_level:
            change_logging(options.logging_level)

        if options.send_data and phone_home_status():
            send_data()

        if options.list_file and phone_home_status():

            run_list(options.list_file)
        elif options.script_file and phone_home_status():
            run_script(options.script_file)
        elif options.create_package and phone_home_status():
            create_package()

        elif options.delete_data and phone_home_status():
            delete_package()
    else:
        logging.error("The cluster has no quorum")
        if options.enable or options.disable or options.logging_level:
            print "The cluster has no quorum"
            sys.stdout.flush()

def signal_handler(signal, frame):
    exit(1)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)
    main()
