#!/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 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
"""

import os
import sys
import socket
import subprocess
import getpass
import globals

__all__ = ['clean_ioc_console', 'screen_dictionary', 'log_session', 'path_to_file', 'environment']

    
def screen_dictionary(screen_cmd):
    
    args = [screen_cmd, '-list']

    if globals.verbose:
        print "Getting a list of screens using ", args 

    screen_list = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].splitlines()

    screend = {}
    for screen_info in screen_list:
        try:
            (pid_and_name, state) = screen_info.split()
        except ValueError:
            continue

        (pid, sep, name) = pid_and_name.partition('.')
    
        screend[name] = {'pid': pid, 'state': state, 'pid_and_name': pid_and_name}

    return screend


def clean_ioc_console(iocname, screen_cmd, prefix_args=[]):
    """
    Cleanup iocConsole sessions for iocname
    """
    
    print 'Initiating cleanup for %s' % (iocname)
    
    if globals.verbose:
        print "Screen command ", screen_cmd

    screen_dict = screen_dictionary(screen_cmd)

    if iocname not in screen_dict:
        print 'No screen found for %s.  %s was not cleaned.' % (iocname, iocname)
        return 0

    sessioninfo = screen_dict[iocname]
    pid = sessioninfo['pid']
    screensessionname = sessioninfo['pid_and_name']
    if globals.verbose:
        print "Screen info for IOC {0} -> pid = {1} screen session name = {2}".format(iocname, pid, screensessionname)

    print 'There is a iocConsole session for IOC %s (pid: %s)' % (iocname, pid)
    answer = raw_input('Are you sure you want to kill the iocConsole session (y/n)? ')
    
    if not answer.strip():
        answer = 'y'
        
    if answer[0].lower() != 'y':
        print 'Clean cancelled.  %s was not cleaned.' % (iocname,)
        return False

    args = prefix_args + ['kill', '-KILL', pid]
    subprocess.call(args)
    if globals.verbose:
        print "Sent the KILL signal to ", pid

    args = prefix_args + [screen_cmd, '-wipe', screensessionname]
    print 'clean_ioc_console: %s' % (' '.join(args))
    try:
        subprocess.check_call(args)
    except subprocess.CalledProcessError, e:
        print 'clean_ioc_console: "%s" returned %s' % (' '.join(args), e.returncode)

    print 'Cleaning of %s complete.' % (iocname,)
    return 0


def log_session(shell, logscript, iocname, effective_username):
    """
    Start a script, indicated by environment variable IOC_LOGSCRIPT to log a
    message indicating that this user has started an iocConsole screen session.
    
    Return without logging if logscript is `None'.
    """
    
    if not logscript:
        return
        
    command = shell + [logscript, iocname, effective_username]
    try:
        subprocess.check_call(command)
    except subprocess.CalledProcessError, e:
        print 'Failed to log iocConsole session for %s by %s.  Error: %s' % (iocname, effective_username, e.returncode)
        return

    print 'Logged new iocConsole session for %s by %s' % (iocname, effective_username)

def path_to_file(dir_list, filename):
    found_path = False
    for path in dir_list:
        file_path = os.path.join(path, filename)
        if os.path.isfile(file_path):
            return file_path
    return ''


def environment(environ=None):
    """
    Return a dictionary of environment settings relevant to iocconsole
    """
    
    if not environ:
        environ = os.environ
    
    env_dict = {}
    env_dict['cwd'] = os.path.abspath(os.getcwd())
    env_dict['selfdir'] = os.path.abspath(os.path.dirname(sys.argv[0]))
    
    # iocCommon directory or
    env_dict['ioc'] = environ.get('IOC')
    
    # IOC_OWNER is unix account under which screen runs    
    # We default this to laci and allow overrides using the IOC_OWNER environment variable
    env_dict['screen_owner'] = 'laci'
    if 'IOC_OWNER' in os.environ:
        env_dict['screen_owner'] = environ.get('IOC_OWNER', 'laci')
    
    # If IOC_OWNER_SHELL is set (to bash or sh), then use it for all shell
    # commands with the login (-l) option.  Note that the .bashrc file is
    # not sourced unless this option is set.  csh and tcsh don't have this
    # restriction so IOC_OWNER_SHELL is not required.
    env_dict['shell'] = [environ.get('IOC_OWNER_SHELL', 'bash')]
    
    if env_dict['shell'][0] in ('bash', 'sh'):
        env_dict['shell'].extend(['-l'])
    
    # IOC_SCREEN is location of screeniocs config file and optional screenrc
    # filename (may be used w the -c option to screen, if it exists in this dir) 
    env_dict['iocdir'] = environ.get('IOC_SCREEN', env_dict['selfdir'])
     
    # IOC_INFO or IOC_DATA or CD_DATA_IOC or current directory provides:
    #  - path of bootparams file.
    #  - location of the screenlog file if screenrc's `deflog' is set to `on'
    #  - the IOC core file dump directory
    env_dict['iocinfo'] = environ.get('IOC_INFO') or \
                          environ.get('IOC_DATA') or \
                          environ.get('CD_DATA_IOC') or \
                          os.getcwd()
    
    # screen utility modified for root privilege
    env_dict['screendir'] = environ.get('SCREENBIN', '/usr/bin')
    env_dict['screen'] = os.path.join(env_dict['screendir'], 'screen')
    
    # Log script
    env_dict['logscript'] = environ.get('IOC_LOGSCRIPT')
    
    # Effective userid (whoami) and hostname
    env_dict['effective_username'] = getpass.getuser()
    env_dict['hostname'] = socket.gethostname()
    
    # Path to default screeniocs file
    default_screeniocs_dirs = (env_dict['cwd'], env_dict['iocdir'], env_dict['selfdir'])
    env_dict['screeniocs'] = path_to_file(default_screeniocs_dirs, 'screeniocs')
    
    return env_dict


def main(ioc_names):
    env = environment()
    with open(env['screeniocs']) as f:
        iocs = load_screeniocs(f)
    
    for ioc in ioc_names:
        try:
            d = iocs[ioc]
            print ioc, d['terminal_server'], d['port'], d['screen_host']
        except KeyError:
            pass



if __name__ == '__main__':
    main(sys.argv[1:])
    sys.exit(0)

