#!/usr/bin/env python
"""
This is the server side component of pyiocconsole. 
This component basically acts as a generator of screen options and command parameters and executes them.
This command should run on the screenhost.
"""

import os
import re
import sys
import time
import optparse
import argparse
import globals
import subprocess
import parseScreenIOCS
import iocConsoleUtils


def main(argv, environ):
    '''
    Control screen options. connectionParams depends on IOC type; for all IOC types first argument is IOC name.
    After the iocName, 
    SIOC - Path to executable
    HIOC - Terminal server that we telnet to and the port
    VIOC - SSH host that we ssh into and the userid.
    '''
    parser = argparse.ArgumentParser(description="Server side component of pyiocconsole. This component basically acts as a generator of screen options and command parameters and executes them.") 
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')
    parser.add_argument('-c', '--cleanup', action='store_true', help='Cleanup any screen sessions for this IOC and exit.')
    parser.add_argument('-s', '--stayup', action='store_true', help='Start a detached screen and periodically restart until a cleanup is done')
    parser.add_argument('-d', '--detach',    action='store_true', help='Do not attach to a newly started screen session. /etc/init.d startup scripts are expected to use this argument to start the screen session and not attach to it.')
    parser.add_argument('-r', '--troubleshoot_screen_startup', action='store_true', help='Troubleshoot the screen startup process. Does not fork a separate process')
    parser.add_argument('-t', '--type',      help="What kind of ioc is this? This determines what we use to connect.")
    parser.add_argument("connectionParams", help="The IOC name", nargs="+")
    args = parser.parse_args()
    
    if args.verbose:
        globals.verbose = True
        
    iocConsoleEnv = iocConsoleUtils.environment()
    iocname = args.connectionParams[0]
    os.unsetenv('SSH_ASKPASS')

    
    if args.cleanup:
        print "Cleaning up any existing screen sessions for ", iocname
        status = iocConsoleUtils.clean_ioc_console(iocname, iocConsoleEnv['screen'])
        if globals.verbose:
            print "After cleaning up any existing screen sessions for ", iocname, "status is", status
        return status
    
    # For SIOC's, for now, we use siocStartup.pl to start the SIOC
    # We may move this later to python.
    siocStartup = os.path.join(os.environ.get('TOOLS'), "script", "siocStart.bash") 
    if args.verbose:
        print "Path to siocStartup.pl", siocStartup
        
    # Check to see if we have an existing session running.        
    screen_dict = iocConsoleUtils.screen_dictionary(iocConsoleEnv['screen'])
    #if globals.verbose:
    #    print "Screens running on this machine", screen_dict
    
    
    if iocname in screen_dict:
        if globals.verbose:
            print 'screen found for "{0}"'.format(iocname)
        cmd = [iocConsoleEnv['screen'], '-r', '-S', '%s/%s' % (iocConsoleEnv['screen_owner'], iocname)]
        if globals.verbose:
            print "Command to join existing session", ' '.join(cmd)

        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError, e:
            print '"{0}" returned {1}'.format(' '.join(cmd), e.returncode)
            return e.returncode
        return 0

    iocType = None    
    if 'type' in args:
        iocType = args.type
        
    screenioc_path = iocConsoleEnv.get('screeniocs')
    iocinfos = parseScreenIOCS.parseScreenIOCs(screenioc_path)
    iocinfo = iocinfos[iocname]
    if iocType:
        # If the caller (iocConsole) has specified a type, we expect it to have specified the other connection parameters as well 
        if iocType == 'SIOC':
            if globals.verbose:
                print "Overriding SIOC executable to ", args.connectionParams[1]
            iocinfo['executable'] = args.connectionParams[1]
        elif iocType == 'HIOC':
            if globals.verbose:
                print "Overriding HIOC terminalserver and port to ", args.connectionParams[1], "and", args.connectionParams[2]  
            iocinfo['terminalserver'] = args.connectionParams[1]
            iocinfo['port'] = args.connectionParams[2]
        elif iocType == 'VIOC':
            if globals.verbose:
                print "Overriding VIOC terminalserver and user to ", args.connectionParams[1], "and", args.connectionParams[2]  
            iocinfo['terminalserver'] = args.connectionParams[1]
            iocinfo['user'] = args.connectionParams[2]
        else:
            print "Unknown type of IOC", iocType
            return 0
    else:
        # If the caller (iocConsole) has not specified a type, we use the defaults from screeniocs 
        iocType = iocinfo['type']
        
    if globals.verbose:
        print "Parameters for launch", iocname, iocType, iocinfo
    
    # We have not found the screen session; let's start it up.
    if iocType == 'SIOC':
        if iocConsoleEnv['hostname'] != iocinfo['screenhost']:
            print "We are attempting to start an IOC on {0} when it is supposed to start on {1}".format(iocConsoleEnv['hostname'], iocinfo['screenhost'])
            return -1
        if globals.verbose:
            print "Confirmed that we are starting the SIOC on the machine as specified by {0}".format(screenioc_path)
        # siocStartup does a pgrep on the siocStartup command ($0) to see if the IOC has already been started
        # iocConsole checks on the screen session.
        # This disconnect can cause some interesting symptoms that are not obvious to debug
        # So, we do the same pgrep check here as well
        siocStartupCheckCommand = siocStartup + ' ' + iocinfo['executable']  + ' st.cmd ' + iocname + (' 1' if args.stayup else ' 0') 
        try:
            siocStartupProcesses = subprocess.check_output(['pgrep',  '-f', siocStartupCheckCommand])
            print "The IOC process", siocStartupCheckCommand, "seems to be already running on the machine outside of iocConsole with processid(s)", siocStartupProcesses.strip(), ". Please kill these and retry iocConsole"
            return -1
        except subprocess.CalledProcessError:
            pass
        
        print "Starting up SIOC", iocname
        command = ['bash', '-l', '-c', '"' + siocStartup + ' ' + iocinfo['executable']  + ' st.cmd ' + iocname + (' 1' if args.stayup else ' 0') +  '"']
        ping_args = []
    elif iocType == 'HIOC':
        print "Starting up HIOC", iocname
        command = ['telnet', iocinfo['terminalserver'], iocinfo['port']]
        ping_args = ['ping', '-c', '1', iocinfo['terminalserver']]
    elif iocType == 'VIOC':
        print "Starting up VIOC", iocname
        ping_args = ['ping', '-c', '1', iocinfo['terminalserver']]
        command = ['ssh', '-x', '-l',  iocinfo['user'],  iocinfo['terminalserver']]
    else:
        print "Unknown IOC type", iocType
        return 1
    
    if globals.verbose:
        print command, ping_args
        
    if ping_args:
        print ' '.join(ping_args)
        try:
            subprocess.check_call(ping_args)
        except subprocess.CalledProcessError, e:
            print 'Pinging the IOC/terminal server using "{0}" returned {1}. Aborting'.format(' '.join(ping_args), e.returncode)
            return e.returncode

    screenrc_path = iocConsoleUtils.pathToScreenRC(iocConsoleEnv, iocname)
    if globals.verbose:
        print "Using screenrc from ", screenrc_path
    
    if screenrc_path:
        screenopts = ['-c', screenrc_path]
    else:
        screenopts = []

    if globals.verbose:
        print "Screen options are", " ".join(screenopts)
    
    # Find log location and remove log file
    ioclogdir = os.path.join(iocConsoleEnv['iocinfo'], iocname)
    if not os.path.isdir(ioclogdir):
        ioclogdir = iocConsoleEnv['iocinfo']
    if globals.verbose:
        print "Logs for IOC {0} are in {1}".format(iocname, ioclogdir)

    screenlog = os.path.join(ioclogdir, 'screenlog.0')
    try:
        os.remove(screenlog)
    except OSError, e:
        print 'Could not remove "%s": %s' % (screenlog, e.strerror)
    
    if args.troubleshoot_screen_startup:
        screen_cmd_args = ['umask 000;', iocConsoleEnv['screen'], '-D', '-m', '-S', iocname, '-t', iocname] + screenopts + command
        if globals.verbose:
            print screen_cmd_args
        screen_cmd = ' '.join(screen_cmd_args)
        print 'Stay up.  Running "%s" in %s' % (screen_cmd, ioclogdir)
        status = 0;
        # Process return code will be 0 when user quits out of telnet.  
        # Automatically restart in this case.  Don't ping first.  If the terminal
        # server is off, wait for it.
        while status == 0:
            status = subprocess.Popen(screen_cmd, shell=True, cwd=ioclogdir).wait()
            if status == 0:
                print iocname, 'should stay up.  Restarting in 5 seconds.'
                time.sleep(5)
    else:
        screen_cmd_args = ['umask 000;', iocConsoleEnv['screen'], '-d', '-m', '-S', iocname, '-t', iocname] + screenopts + command
        if globals.verbose:
            print screen_cmd_args
        screen_cmd = ' '.join(screen_cmd_args)
        print 'Running "%s" in %s' % (screen_cmd, ioclogdir)
        process = subprocess.Popen(screen_cmd, shell=True, cwd=ioclogdir, stdin=sys.stdin, stdout=sys.stdout).wait()

        if args.detach:
            if globals.verbose:
                print "Detach - so not attaching to forked screen process"
            return 0

        wait = 0;
        max_wait_time = 10;
        #time.sleep(1)

        screen_dict = iocConsoleUtils.screen_dictionary(iocConsoleEnv['screen'])

        while iocname not in screen_dict:
            wait += 1
            if wait > max_wait_time:
                print 'Timeout trying to connect to multiuser screen session.'
                if iocType == 'SIOC':
                    print "It is possible that the process for your SIOC - {0} died and screen exited. If you use verbose, the screenlog.0 will be shown after this message".format(iocinfo['executable'])
                if globals.verbose:
                    if os.path.exists(screenlog):
                        time.sleep(1)
                        subprocess.check_call(['less', '-r', screenlog])
                    else:
                        print "Cannot find screenlog.0 using ", 
                return 1
            time.sleep(1)
            if globals.verbose:
                print "Looking for", iocname, "in screen -ls"
            screen_dict = iocConsoleUtils.screen_dictionary(iocConsoleEnv['screen'])
            
        if globals.verbose:
            print 'screen found for "{0}"'.format(iocname)
        cmd = [iocConsoleEnv['screen'], '-r', '-S', '%s/%s' % (iocConsoleEnv['screen_owner'], iocname)]
        if globals.verbose:
            print "Command to join existing session", ' '.join(cmd)

        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError, e:
            print '"{0}" returned {1}'.format(' '.join(cmd), e.returncode)
            return e.returncode
        return 0

    return 0


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

