#!/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.
"""
from __future__ import print_function

import os
import re
import sys
import time
import optparse
import argparse
import globals
import subprocess
import parseScreenIOCS
import iocConsoleUtils
from datetime import datetime


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('-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('-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]
    os.unsetenv('SSH_ASKPASS')

    
    if args.cleanup:
        print("Cleaning up any existing screen sessions for {0}".format(iocname))
        status = iocConsoleUtils.clean_ioc_console(iocname, iocConsoleEnv['screen'])
        if globals.verbose:
            print("After cleaning up any existing screen sessions for {0} status is {1}".format(iocname, 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.bash") 
    if args.verbose:
        print("Path to siocStartup.pl {0}".format(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} {1}"'.format(iocname, screen_dict[iocname]))

        if args.detach:
            print('ERROR: {0} is already running'.format(iocname))
            if globals.verbose:
                print("Detach - so not attaching to forked screen process")
            return 0

        cmd = [iocConsoleEnv['screen'], '-r', '-S', '%s/%s' % (iocConsoleEnv['screen_owner'], screen_dict[iocname].get('pid_and_name', iocname))]
        if globals.verbose:
            print("Command to join existing session {0}".format(' '.join(cmd)))

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

    iocType = None    
    if 'type' in args:
        iocType = args.type
        
    screenioc_path = iocConsoleEnv.get('screeniocs')
    iocinfos = parseScreenIOCS.parseScreenIOCs(screenioc_path)
    iocinfo = iocinfos[iocname]
    if iocType:
        # If the caller (iocConsole) has specified a type, we expect it to have specified the other connection parameters as well 
        if iocType == 'SIOC':
            if globals.verbose:
                print("Overriding SIOC executable to {0}".format(args.connectionParams[1]))
            iocinfo['executable'] = args.connectionParams[1]
        elif iocType == 'HIOC':
            if globals.verbose:
                print("Overriding HIOC terminalserver and port to {0} and {1}".format(args.connectionParams[1], args.connectionParams[2]))
            iocinfo['terminalserver'] = args.connectionParams[1]
            iocinfo['port'] = args.connectionParams[2]
        elif iocType == 'VIOC':
            if globals.verbose:
                print("Overriding VIOC terminalserver and user to {0} and {1}".format(args.connectionParams[1], args.connectionParams[2]))
            iocinfo['terminalserver'] = args.connectionParams[1]
            iocinfo['user'] = args.connectionParams[2]
        else:
            print("Unknown type of IOC".format(iocType))
            return 0
    else:
        # If the caller (iocConsole) has not specified a type, we use the defaults from screeniocs 
        iocType = iocinfo['type']
        
    if globals.verbose:
        print("Parameters for launch {0} {1} {2}".format(iocname, iocType, iocinfo))

    # We have not found the screen session; let's start it up.
    if iocType == 'SIOC':
        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))

        # Use startup.cmd if it exists; otherwise, use st.cmd
        main_st_cmd = 'startup.cmd'
        alt_st_cmd = 'st.cmd'
        ioc_path = os.path.join(os.environ.get('EPICS_IOCS'), iocname)
        main_st_path = os.path.join(ioc_path, main_st_cmd)
        alt_st_path = os.path.join(ioc_path, alt_st_cmd)
        if os.path.exists(main_st_path):
            startup_cmd = main_st_cmd
        elif os.path.exists(alt_st_path):
            startup_cmd = alt_st_cmd
            if globals.verbose:
                print("%s not found in %s. Using %s instead" % (main_st_cmd, ioc_path, alt_st_cmd))
        else:
            print("ERROR: Cannot find %s or %s in %s" % (main_st_cmd, alt_st_cmd, ioc_path))
            return 1

        # siocStartup does a pgrep on the siocStartup command ($0) to see if the IOC has already been started
        # iocConsole checks on the screen session.
        # This disconnect can cause some interesting symptoms that are not obvious to debug
        # So, we do the same pgrep check here as well
        siocStartupCheckCommand = siocStartup + ' ' + iocinfo['executable']  + ' ' + startup_cmd + ' ' + iocname + (' 1' if args.stayup else ' 0') 
        try:
            siocStartupProcesses = subprocess.check_output(['pgrep',  '-f', siocStartupCheckCommand])
            print("The IOC process {0} seems to be already running on the machine outside of iocConsole with "
                  "processid(s) {1}. Please kill these and retry iocConsole".format(siocStartupCheckCommand,
                                                                                    siocStartupProcesses.strip()))
            return -1
        except subprocess.CalledProcessError:
            pass

        print("Starting up SIOC".format(iocname))
        command = ['bash', '-l', '-c', '"' + siocStartup + ' ' + iocinfo['executable']  + ' ' + startup_cmd + ' ' + iocname + (' 1' if args.stayup else ' 0') +  '"']
        ping_args = []
    elif iocType == 'HIOC':
        print("Starting up HIOC".format(iocname))
        command = ['telnet', iocinfo['terminalserver'], iocinfo['port']]
        ping_args = ['ping', '-c', '1', iocinfo['terminalserver']]
    elif iocType == 'VIOC':
        print("Starting up VIOC".format(iocname))
        ping_args = ['ping', '-c', '1', iocinfo['terminalserver']]
        command = ['ssh', '-x', '-l',  iocinfo['user'],  iocinfo['terminalserver']]
    else:
        print("Unknown IOC type".format(iocType))
        return 1
    
    if globals.verbose:
        print("{0} {1}".format(command, ping_args))

    if ping_args:
        print(' '.join(ping_args))
        try:
            subprocess.check_call(ping_args)
        except subprocess.CalledProcessError as e:
            print('Pinging the IOC/terminal server using "{0}" returned {1}. Aborting'.format(' '.join(ping_args),
                                                                                              e.returncode))
            return e.returncode

    screenrc_path = iocConsoleUtils.pathToScreenRC(iocConsoleEnv, iocname)
    if globals.verbose:
        print("Using screenrc from {0}".format(screenrc_path))

    if screenrc_path:
        screenopts = ['-c', screenrc_path]
    else:
        screenopts = []

    if globals.verbose:
        print("Screen options are {0}".format(" ".join(screenopts)))

    # Find log location and back up 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')
    if os.path.exists(screenlog):
        now = datetime.now()
        curr_timestamp = now.strftime('%Y%m%d%H%M%S')
        backup_screenlog = '{0}-{1}'.format(screenlog, curr_timestamp)
        try:
            os.rename(screenlog, backup_screenlog)
            if globals.verbose:
                print('Renaming "{0}" to "{1}"'.format(screenlog, backup_screenlog))
        except OSError as e:
            print('Could not rename "{0}" to "{1}"'.format(screenlog, backup_screenlog))
    
    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('{0} should stay up.  Restarting in 5 seconds.'.format(iocname))
                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.detach:
            if globals.verbose:
                print("Detach - 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 iocType == '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(
                            iocinfo['executable']))
                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 {0} in screen -ls".format(iocname))
            screen_dict = iocConsoleUtils.screen_dictionary(iocConsoleEnv['screen'])
            
        if globals.verbose:
            print('screen found for "{0} {1}"'.format(iocname, screen_dict[iocname]))
        cmd = [iocConsoleEnv['screen'], '-r', '-S', '%s/%s' % (iocConsoleEnv['screen_owner'], screen_dict[iocname].get('pid_and_name', iocname))]
        if globals.verbose:
            print("Command to join existing session {0}".format(' '.join(cmd)))

        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError as 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)

