#!/usr/bin/env python
"""
third level iocconsole tool for connecting to iocs

iocConsole program provides a common mechanism for connecting 
to VME IOC console serial lines as well as soft IOC virtual terminal 
sessions. It takes advantage of gnu screen utility to provide a multiuser
session running telnet 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 scroolback history buffer
    - allows multiple simultaneous connections - anything typed in one
      session appears in all of them - more than one person can be viewing
"""

import os
import re
import sys
import time
import optparse
import subprocess

import iocconsole_R1_0_1 as iocconsole


def process_options(argv):
    """
    Return parsed command-line options found in the list `argv', or
    `sys.argv[1:]' if `argv' is `None'.
    """

    short_usage = """%prog TERMSERV PORT IOCNAME [options]
       %prog TERMSERV PORT IOCNAME STAYUP [options]"""
       
    full_usage = short_usage + """
  TERMSERV      Name of term. server for ioc (e.g. b5as)
                    - if no terminal server, then this is node name
                    - if soft ioc, then this is the full executable name
  PORT          Port number for ioc (e.g. 2001)
                    - if no terminal server, then this is 'telnet' or 'rlogin'
                      (telnet can be postfixed with port number)
                    - if soft ioc, then this is 'sioc'
                    - if ssh terminal server, then port number is prefixed with 'ssh' (e.g. ssh3033)
  IOCNAME       Name of ioc
  STAYUP        Automatic restart (0=no, 1=yes)"""
  
    version = '%prog 0.1'

    parser = optparse.OptionParser(usage=full_usage, version=version)

    parser.add_option('-s', '--stayup',
                      action='store_const', const='1', dest='stayup',
                      help='start a detached screen and periodically restart until a cleanup is done')

    parser.set_defaults(stayup='0')
                        
    if argv is None:
        argv = sys.argv[1:]

    (options, arg_list) = parser.parse_args(argv)

    if len(arg_list) < 3:
        parser.usage = short_usage
        parser.error("Too few arguments")

    args = {}
    (args['ts'], args['protocol_and_port'], args['iocname']) = arg_list[0:3]
    
    if len(arg_list) >= 4:
        args['stayup'] = arg_list[3]

    if 'stayup' in args:
        options.stayup = args['stayup']
    
    matches = re.match('(?P<protocol>[a-zA-Z]*)(?P<port>\d*)', args['protocol_and_port'])
    args['protocol'] = matches.group('protocol').lower()
    args['port'] = matches.group('port')
    
    return (options, args)


def main(argv, environ):
    prog = os.path.basename(sys.argv[0])
    env = iocconsole.environment(environ)
    (options, args) = process_options(argv)
    
    screen_dict = iocconsole.screen_dictionary(env['screen'])
    
    if args['iocname'] in screen_dict:
        print '{0}: screen found for "{1}"'.format(prog, args['iocname'])
        return 0
    
    # Build command
    if env['os'] == 'SunOS':
        ping_args = ['ping', '-c', '1', args['ts']]
    else:
        ping_args = ['/usr/bin/fping', args['ts']]
    
    if args['protocol'] == 'telnet':
        print 'telnet -> port =', args['port']
        command = [args['protocol']]
        console_args = [args['ts'], args['port']]
    
    if args['protocol'] == 'rlogin':
        print 'Connecting to node name (not terminal srv)...'
        command = [args['protocol']]
        console_args = [args['ts']]
        if env['os'] == 'SunOS':
            ping_args = ['ping', args['ts']]
    
    if args['protocol'] == 'sioc':
        command = [env['shell'], 'siocStart.pl']
        console_args = [args['ts'], 'st.cmd', args['iocname'], options.stayup]
        options.stayup = '0'
        ping_args = []
    
    if args['protocol'] == 'ssh':
        print 'ssh terminal server -> port =', args['port']
        command = ['ssh', '-x', '-l', env['screen_owner']]
        console_args = [args['ts'], '-p', args['port']]
    
    if not args['protocol']:
        print 'terminal server'
        command = ['telnet']
        console_args = [args['ts'], args['port']]
    
    if not options.stayup and 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

    # Use screenrc if one can be found
    screenrc_dirs =  (env['cwd'],
                      os.path.join(env['iocdir'], args['iocname']),
                      env['selfdir'])
    
    screenrc_path = iocconsole.path_to_file(screenrc_dirs, 'screenrc')
    
    if screenrc_path:
        screenopts = ['-c', screenrc_path]
    else:
        screenopts = []
    
    # Find log location and remove log file
    ioclogdir = os.path.join(env['iocinfo'], args['iocname'])
    if not os.path.isdir(ioclogdir):
        ioclogdir = env['iocinfo']

    screenlog = os.path.join(ioclogdir, 'screenlog.0')
    try:
        os.remove(screenlog)
    except OSError, e:
        print 'Could not remove "%s": %s' % (screenlog, e.strerror)
    
    if int(options.stayup):
        screen_cmd_args = ['umask 000;', env['screen'], '-D', '-m', '-S', args['iocname'], '-t', args['iocname']] + screenopts + command + console_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 args['iocname'], 'should stay up.  Restarting in 5 seconds.'
                time.sleep(5)
    else:
        screen_cmd_args = ['umask 000;', env['screen'], '-d', '-m', '-S', args['iocname'], '-t', args['iocname']] + screenopts + command + console_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()

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

        screen_dict = iocconsole.screen_dictionary(env['screen'])

        while args['iocname'] not in screen_dict:
            wait += 1
            if wait > max_wait_time:
                print 'Timeout waiting for Multiuser session', ' '.join(console_args)
                return 1
            time.sleep(1)
            screen_dict = iocconsole.screen_dictionary(env['screen'])

    return 0


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

