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

The 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 sys
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")

    keys = ('ts', 'port', 'iocname', 'stayup')
    args = dict(zip(keys, arg_list))

    if 'stayup' in args:
        options.stayup = args['stayup']
    
    return (options, args)



def main(argv, environ):
    prog = os.path.basename(sys.argv[0])
    env = iocconsole.environment(environ)
    (options, args) = process_options(argv)
    
    cmd = env['shell']
    cmd.extend(('pyiocscreenstart', args['ts'], args['port'], args['iocname'], options.stayup))

    print '{0}:'.format(prog), ' '.join(cmd)
    
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError, e:
        print '{0}: "{1}" returned {2}'.format(prog, ' '.join(cmd), e.returncode)
        return e.returncode
    
    cmd = [env['screen'], '-r', '-S', '%s/%s' % (env['screen_owner'], args['iocname'])]

    print '{0}:'.format(prog), ' '.join(cmd)

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


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

