#!/usr/bin/env python
"""
common mechanism for connecting to IOC terminal sessions

iocconsole takes advantage of gnu screen utility to provide a multiuser
session running telnet/ssh to manage an ioc console session.

    - telnet session to ioc continues to run even when no users are attached
      to the screen session
    - ioc console output is captured and can be viewed by subsequent sessions
    - maintains scrollback history buffer
    - allows multiple simultaneous connections to the same console - anything
      typed in one session appears in all consoles of the same sessions
      
Note that ioc console 

"""
from __future__ import print_function

import os
import sys
import subprocess
import argparse
import globals
import iocConsoleUtils
import parseScreenIOCS

def load_screeniocs(path):
    screen_iocs = None
    try:
        with open(path) as screenioc_file:
            screen_iocs = iocConsoleUtils.load_screeniocs(screenioc_file)
    except IOError as e:
        print('Error: {0}'.format(e))

    return screen_iocs


def launchVIOCConsole(ioc, iocInfo):
    ''' Launch SSH session for VIOC console directly from the client. This is mainly because the VIOC being linux has to launch it's ioc program using screen; so a screen session is already running'''
    ping_args = ['ping', '-c', '1', iocInfo['terminalserver']]
    try:
        subprocess.check_call(ping_args)
    except subprocess.CalledProcessError as e:
        print('Cannot ping machine {0} hosting VIOC {1} using {2}'.format(iocInfo['terminalserver'], ioc,
                                                                          ' '.join(ping_args)))
        return e.returncode

    sshargs = "ssh -t " + iocInfo['user'] + '@' + iocInfo['terminalserver'] +  ' screen' + ' -x ' + ioc
    if globals.verbose:
        print("For VIOC {0}, executing ssh with command {1}".format(ioc, sshargs))
    subprocess.call(sshargs, shell=True)
    return 0



def process_options():
    """Set up and process the command line options"""

    parser = argparse.ArgumentParser(description="Connects to the screen session that is capturing the console for the IOC.", 
                                     epilog="pyiocconsole typically works in conjunction with the screeniocs file for this installation - " + os.path.join(os.getenv("IOC_SCREEN", "${IOC_SCREEN}"), 'screeniocs') 
                                     +  ". The ioc name is the first column in the screeniocs file and is the hard ioc node name or micro name or soft ioc name. Soft ioc's are started via the 'siocStart' command")
    parser.add_argument('-v', '--verbose',   action='store_true', help='Enable verbose logging')
    parser.add_argument('-c', '--cleanup',   action='store_true', help="Kills screen session(s) named <iocname>")
    parser.add_argument('-s', '--stayup',    action='store_true', help='Starts the SIOC in a while loop - if the user exits from the IOC shell or if the process dies; the SIOC is started again after a 5 second pause.')
    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('-n', '--norestart', action='store_true', help='Only connect to an existing screen session. Do not start a new screen session if one does not already exist.')
    parser.add_argument('-l', '--list', action='store_true', help='List the iocConsole configuration for an IOC. If you do not specify the IOC, this command displays the screen info for all IOCs.')
    parser.add_argument('--troubleshoot_screen_startup',   action='store_true', help="Troubleshoot's the screen startup process. You can try using this command if you find your screen session terminating immediately on startup. This is often not very useful so hold your complaints.")
    parser.add_argument('-t', "--terminalserver", help="Override the terminal server node name for hard IOC's connecting thru a terminal server. Also for overriding the ssh server for VIOC's.")
    parser.add_argument('-p', "--port", help="Override the port number for hard IOC's connecting thru a terminal server.")
    parser.add_argument('-e', "--executable", help="Override the path to the executable for soft IOCS's.")
    parser.add_argument('-u', "--user", help="Override the username used in the ssh command for VIOC's")
    parser.add_argument('-m', "--screenhost", help="Specify the machine where 'screen' is run - aka screenhost")
    parser.add_argument('-r', '--run', metavar='SCREENHOST', nargs='?', default='', help='List the IOCs running on a screenhost. If you do not specify the host, the current host is used.')
    parser.add_argument("iocname", help="The IOC name", nargs="?")

    args = parser.parse_args()

    return args


def main():
    iocConsoleEnv = iocConsoleUtils.environment()
    args = process_options()
    
    if args.verbose:
        globals.verbose = True
    
    iocname              = args.iocname
    screen_session_name  = args.iocname
    screenioc_path       = iocConsoleEnv.get('screeniocs')
    screen_command       = iocConsoleEnv['screen']
    defaultScreenOwner   = iocConsoleEnv['screen_owner']

    if args.run:
        screen_host = args.run
        screen_owner = defaultScreenOwner
        if globals.verbose:
            print("Current running as {0} on machine {1}".format(screen_owner, screen_host))

        sshargs = ['ssh', '-x', '-t', '-l', screen_owner, screen_host, screen_command, '-ls', 'sioc']
        if globals.verbose:
            print("ssh args for {0} on {1}; ------ {2}".format(screen_owner, screen_host, " ".join(sshargs)))

        subprocess.call(sshargs)
        return 0

    elif args.run is None:
        print("-r specified with no screenhost; using current host")
        screenargs = [screen_command, '-ls', 'sioc']
        if globals.verbose:
            print("Screen args: {0}".format(screenargs))

        subprocess.call(screenargs)
        return 0

    if globals.verbose:
        print('Using screeniocs file: {0}'.format(screenioc_path))
    iocs = parseScreenIOCS.parseScreenIOCs(screenioc_path)
    
    if args.list:
        if iocs is None:
            if globals.verbose:
                print("Empty screen iocs file {0}".format(screenioc_path))
            return 1
        if not iocname or iocname == 'ALL':
            for (ioc, info) in sorted(iocs.items(), key=lambda x: x[0]):
                print("{0} ==> {1}".format(ioc, info))
        else:
            if iocname in iocs:
                print("{0} ==> {1}".format(iocname, iocs[iocname]))
            else:
                print("Cannot seem to find definition for {0} in {1}".format(iocname, screenioc_path))
        return 0
    
    if not iocname:
        print("To connect to an IOC, please specify the IOC name as it is outlined in screeniocs - {0}".format(
            screenioc_path))
        return 1
    
    if iocname not in iocs:
        print("Cannot find info for IOC {0} in {1}".format(iocname, screenioc_path))
        return 1
    
    iocInfo = iocs[iocname]

    if globals.verbose:
        print("Before the overrides, the configuration for ioc {0} is {1}".format(iocname, iocInfo))
    
    if args.terminalserver:
        if globals.verbose:
            print("Overriding the terminal server to {0}".format(args.terminalserver))
        iocInfo['terminalserver'] = args.terminalserver
    
    if args.port:
        if globals.verbose:
            print("Overriding the port to {0}".format(args.port))
        iocInfo['port'] = args.port

    if args.executable:
        if globals.verbose:
            print("Overriding the executable to {0}".format(args.executable))
        iocInfo['executable'] = args.executable
        
    if args.user:
        if globals.verbose:
            print("Overriding the user to {0}".format(args.user))
        iocInfo['user'] = args.user

    if args.screenhost:
        if globals.verbose:
            print("Overriding the screenhost (using the machine argument) to {0}".format(args.screenhost))
        iocInfo['screenhost'] = args.screenhost


    if 'screen_owner' not in iocInfo:
        if globals.verbose:
            print("Defaulting the screen owner from the environment to {0}".format(defaultScreenOwner))
        iocInfo['screen_owner'] = defaultScreenOwner

    if globals.verbose:
        print("After the overrides, the configuration for ioc {0} is {1}".format(iocname, iocInfo))

    # For VIOC's (which are Linux devices), we use the screen on the box itself. This is per Ernest
    if iocInfo['type'] == 'VIOC':
        if args.cleanup or args.norestart or args.stayup or args.detach:
            print('''For VIOC's, many arguments do not make sense.
The IOC process is started as part of a screen session on the IOC itself.
The VIOC may not have all the infrastructure available to it to support cleanup/norestart/autostart/detach etc.''')
            return -1
        return launchVIOCConsole(iocname, iocInfo)

        


    screen_host = iocInfo['screenhost'] 
    screen_owner = iocInfo['screen_owner'] 
    
    if globals.verbose:
        print("Current running as ", screen_owner, " on machine", screen_host)
        print("Current running as {0} on machine {1}".format(screen_owner, screen_host))


    # The -x is to turn off X-forwarding, the -t is to force the allocation of a tty
    # Note the -t argument does not set the path correctly on the remote side.
    # So we need to invoke bash -l -c with correct quoting around the arguments
    sshargs = ['ssh', '-x', '-t', '-l', screen_owner, screen_host, 'bash', '-l', '-c', '"']
    finalTerminator = '"'
    
    if iocConsoleEnv['hostname'] == iocInfo['screenhost']:
        if iocConsoleEnv['effective_username'] == screen_owner:
            sshargs = []
            finalTerminator = ''
        elif iocConsoleEnv['effective_username'] == "root":
            sshargs = ['su', '-l', screen_owner]
            finalTerminator = ''
    if globals.verbose:
        print("ssh args for {0} on {1}; ------ {2}".format(screen_owner, screen_host, " ".join(sshargs)))

    if args.cleanup:
        sshargs.append('pyiocscreen.py')
        if globals.verbose:
            sshargs.append('-v')
        sshargs.append('-c')
        sshargs.append(iocname)
        sshargs.append(finalTerminator)
        finalargs = [str(a) for a in sshargs]
        print('{0}:'.format(' '), ' '.join(finalargs))
        if globals.verbose:
            print("Final sets of args {0}".format(finalargs))
        subprocess.call(finalargs)
        return 0
    
    if args.norestart:
        owner_slash_session = '/'.join((screen_owner, screen_session_name))
        sshargs.extend([screen_command, '-r', '-S', owner_slash_session, finalTerminator])
    else:
        sshargs.append('pyiocscreen.py')
        if globals.verbose:
            sshargs.append('-v')
        if args.stayup:
            sshargs.append('--stayup')
        if args.detach:
            sshargs.append('--detach')
        if iocInfo['type'] == 'SIOC':
            sshargs.extend(('-t', 'SIOC', iocname, iocInfo['executable'], finalTerminator))
        elif iocInfo['type'] == 'HIOC':
            sshargs.extend(('-t', 'HIOC', iocname, iocInfo['terminalserver'], iocInfo['port'], finalTerminator))
        elif iocInfo['type'] == 'VIOC':
            sshargs.extend(('-t', 'VIOC', iocname, iocInfo['terminalserver'], iocInfo['user'], finalTerminator))
        else:
            print("Unknown IOC type {0} {1}".format(iocInfo['type'], iocInfo))
            return 1
    
    finalargs = [str(a) for a in sshargs]
    print('{0}:'.format(' '), ' '.join(finalargs))
    
    if globals.verbose:
        print("Final sets of args {0}".format(finalargs))
    # TODO - iocConsoleUtils.log_session(iocConsoleEnv['shell'], iocConsoleEnv['logscript'], iocname, iocConsoleEnv['effective_username'])
    subprocess.call(finalargs)
    return 0


if __name__ == '__main__':
    status = main()
    sys.exit(status)

