#!/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('-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]
    
    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.pl") 
    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
    
    # We have not found the screen session; let's start it up.
    if args.type == 'SIOC':
        screenioc_path = iocConsoleEnv.get('screeniocs')
        iocinfo = parseScreenIOCS.parseScreenIOCs(screenioc_path)[iocname]
        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)
        print "Starting up SIOC", args.connectionParams
        command = ['bash', '-l', '-c', '"' + siocStartup + ' ' + args.connectionParams[1] + ' st.cmd ' + args.connectionParams[0] + (' 1' if args.stayup else ' 0') +  '"']
        ping_args = []
    elif args.type == 'HIOC':
        print "Starting up HIOC", args.connectionParams
        command = ['telnet', args.connectionParams[1], args.connectionParams[2]]
        ping_args = ['ping', '-c', '1', args.connectionParams[1]]
    elif args.type == 'VIOC':
        print "Starting up VIOC", args.connectionParams
        ping_args = ['ping', '-c', '1', args.connectionParams[1]]
        command = ['ssh', '-x', '-l',  args.connectionParams[2],  args.connectionParams[1]]
    else:
        print "Unknown IOC type", args.type
        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 '{0}: "{1}" returned {2}'.format(prog, ' '.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.stayup:
            if globals.verbose:
                print "Stayup - 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 args.type == '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(args.connectionParams[1])
                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)

