#! /usr/local/bin/python

# Copyright C 2002-2003 by Isilon Systems, Inc. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
#
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
#
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems.
#
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

import os
import sys
import signal
import getopt
import json

import isi.rest as rest 
import isi.misc as misc
import isi.celog.celog_config_api


DEFAULT_ANS = 'yes'
ANS_YES = 'yes'
ANS_NO = 'no'
DELIM = '::'
ESRS_FILE = '/var/tmp/esrs_config.txt'

def save_esrs_prompt(info):

    # Save info to a file
    fd = open(ESRS_FILE, 'w')
    if info:
        fd.write('enabled%s%s\n' % (DELIM, info['enabled']))
        fd.write('primary_esrs_gateway%s%s\n' \
                 % (DELIM, info['primary_esrs_gateway']))
        fd.write('secondary_esrs_gateway%s%s\n' \
                 % (DELIM, info['secondary_esrs_gateway']))
        fd.write('use_smtp_failover%s%s\n' % (DELIM, info['use_smtp_failover']))
        fd.write('email_customer_on_failure%s%s\n' \
                 % (DELIM, info['email_customer_on_failure']))
        fd.write('gateway_access_pools%s%s\n' \
                 % (DELIM, info['gateway_access_pools']))
        fd.write('company%s%s\n' % (DELIM, info['company']))
        fd.write('contact%s%s\n' % (DELIM, info['contact']))
        fd.write('phone%s%s\n' % (DELIM, info['phone']))
        fd.write('email%s%s\n' % (DELIM, info['email']))

    fd.close()

def configure_esrs():
    try:
        fd = open(ESRS_FILE, 'r')
        info = {}

        for line in fd.readlines():
            line = line.rstrip()
            key, val = line.split(DELIM)
            if key == 'enabled':
                info['enabled'] = val
            elif key == 'primary_esrs_gateway':
                info['primary_esrs_gateway'] = val
            elif key == 'secondary_esrs_gateway':
                info['secondary_esrs_gateway'] = val
            elif key == 'use_smtp_failover':
                info['use_smtp_failover'] = val
            elif key == 'email_customer_on_failure':
                info['email_customer_on_failure'] = val
            elif key == 'gateway_access_pools':
                info['gateway_access_pools'] = val
                tmp = ""
                for value in info['gateway_access_pools'].split(','):
                    tmp = tmp + value + ','
                tmp = tmp[:-1]
                info['gateway_access_pools'] = tmp
            elif key == 'company':
                info['company'] = val
            elif key == 'contact':
                info['contact'] = val
            elif key == 'phone':
                info['phone'] = val
            elif key == 'email':
                info['email'] = val

        fd.close()
    except IOError:
        # No file means don't do anything.
        return

    cmd = "isi remotesupport connectemc modify --email-customer-on-failure=%s" \
          " --enabled=%s --primary-esrs-gateway=%s"  \
          " --secondary-esrs-gateway=%s --use-smtp-failover=%s --gateway_access_pools=%s" % \
          (info['email_customer_on_failure'], info['enabled'], \
          info['primary_esrs_gateway'], \
          info['secondary_esrs_gateway'], info['use_smtp_failover'], \
          info['gateway_access_pools'])
    commit(info)
    os.system(cmd)

    return


def commit(contact_settings):
    __celog_cfg__ = isi.celog.celog_config_api.CelogConfigAPI()
    if not misc.ifs_mounted():
        return

    # Default values
    exists = True
    ans = ANS_YES

    new_contact_settings = {}
    if contact_settings['company']:
        new_contact_settings['company'] = contact_settings['company']
    if contact_settings['contact']:
        new_contact_settings['primary_name'] = contact_settings['contact']
    if contact_settings['phone']:
        new_contact_settings['primary_phone1'] = contact_settings['phone']
    if contact_settings['email']:
        new_contact_settings['primary_email'] = contact_settings['email']
    if new_contact_settings:
        try:
            __celog_cfg__.set_contact_settings(new_contact_settings)
        except Exception as e:
            print "Unable to set contact settings: %s" % e

def prompt_info(prompt, required = False):
    done = 0
    val = ''

    while not done:
        # Note that KeyboardInterrupt is handled elsewhere
        val = raw_input(prompt)
        if not required or val:
            done = 1

    return val

def prompt_info_bool(prompt, required=False):
    val = 'no'
    while (val != 'true' and val != 'false'):
        val = prompt_info(prompt, required)
        if val == 'yes' or val == 'y':
            val = 'true'
        elif val == 'no' or val == 'n':
            val = 'false'
        elif val == '':
            val = 'false'
    return val

def show_current_settings():
    '''Show the current configuration'''

    __celog_cfg__ = isi.celog.celog_config_api.CelogConfigAPI()
    # Get the current contact settings
    contact_settings = __celog_cfg__.get_contact_settings()

    print "\n\tCurrent ESRS Contact Settings:"

    # Show contact status
    print "\t%-20s: %s" % ("Company", contact_settings['company'])
    print "\t%-20s: %s" % ("Location", contact_settings['location'])
    print "\t%-20s: %s" % ("Primary Name", contact_settings['primary_name'])
    print "\t%-20s: %s" % ("Phone", contact_settings['primary_phone1'])
    print "\t%-20s: %s" % ("Email", contact_settings['primary_email'])
    print "\t%-20s: %s" % ("Phone 2", contact_settings['primary_phone2'])
    print "\t%-20s: %s" % ("Secondary Name", contact_settings['secondary_name'])
    print "\t%-20s: %s" % \
            ("Secondary Phone", contact_settings['secondary_phone1'])
    print "\t%-20s: %s" % \
            ("Secondary Phone 2", contact_settings['secondary_phone2'])
    print "\t%-20s: %s" % \
            ("Secondary Email", contact_settings['secondary_email'])
    print "\n"

def handle_console(extra):
    """
    extra - Collect extra information (i.e. alert contact information)
    """

    # Get the current contact settings
    done = 0
    val = ''

    while not done:
        done = 1    # assume this will only run once
        info = {}

        question = "Would you like to enable ESRS? [%s] " % DEFAULT_ANS
        try:
            val = raw_input(question)
        except KeyboardInterrupt:
            break

        if val == '':
            val = DEFAULT_ANS
        if val == 'yes' or val == 'y':
            # Defaults

            # Prompt for contact information
            if extra:
                info['company'] = ''
                info['contact'] = ''
                info['phone'] = ''
                info['email'] = ''
                info['enabled'] = 'true'
                info['primary_esrs_gateway'] = ''
                info['secondary_esrs_gateway'] = ''
                info['use_smtp_failover'] = 'no'
                info['email_customer_on_failure'] = 'no'
                info['gateway_access_pools'] = []

                try:
                    print "\nEdit contact information (RETURN to keep " + \
                            "current setting):"
                    info['company'] = \
                            prompt_info('Please enter company name (%s): '
                            % info['company'])
                    info['contact'] = \
                            prompt_info('Please enter contact name (%s): '
                            % info['contact'])
                    info['phone'] = \
                            prompt_info('Please enter contact phone (%s): '
                            % info['phone'])
                    info['email'] = \
                            prompt_info('Please enter contact email (%s): '
                            % info['email'])
                    info['primary_esrs_gateway'] = \
                            prompt_info('Please enter a primary ESRS gateway (%s): '
                            % info['primary_esrs_gateway'])
                    info['secondary_esrs_gateway'] = \
                            prompt_info('Please enter a secondary ESRS gateway (%s): '
                            % info['secondary_esrs_gateway'])
                    info['use_smtp_failover'] = \
                            prompt_info_bool('Use SMTP failover? (%s) '
                            % info['use_smtp_failover'])
                    info['email_customer_on_failure'] = \
                            prompt_info_bool('Send email on failure? (%s) '
                            % info['email_customer_on_failure'])
                    info['gateway_access_pools'] = \
                            prompt_info('Enter a comma separated list of subnets: ')

                except KeyboardInterrupt:
                    pass

                save_esrs_prompt(info)
        elif val != 'no' and val != 'n':
            print ""
            print "Please enter one of 'yes' or 'no'"
            print ""
            done = 0

    return 1 # Always kill LCD.

def alert_prompt(extra):
    def handle_signal(signal, stack_frame):
        sys.exit(0)

    # We use SIGINT here, because raw_input blocks SIGTERM
    signal.signal(signal.SIGINT, handle_signal)

    done = 0

    done = handle_console(extra)


def main(argv):

    def usage():
        print "Usage: isi_promptesrs [-e] [-c]"
        print ""
        print "Configure settings:"
        print ""
        print "Options:"
        print "  -e\t\tEdit ESRS config information"
        print "  -c\t\tCommit ESRS config information"

    try:
        opts, args = getopt.getopt(argv, 'ecs')
    except Exception:
        usage()
        return 1

    extra = False
    config = False

    # Parse arguments;
    for (opt, arg) in opts:
        if opt == '-e':
            extra = True
        if opt == '-c':
            config = True

    try:
        if config:
            configure_esrs()
        else:
            alert_prompt(extra)
        return 0
    except:
        # XXX This raise is intentional, for now, to aid in bug-fixing.
        raise
        return -1

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
