'''The client side of the multi_facility_process_helper.
Mostly a utility class with a lot of convenience methods.'''
import sys
import os.path
import json
import subprocess
import globals
import toolconfig


def executeCommandsOnFacility(facility, commandsAndArgs):
    '''Executes a list of commands on the specified facility using ssh and the multi_facility_process_helper. 
    facility - This is the facility name.
    commandsAndArgs - A list of tuples - each tuple has two components. First component is a string command. Second command is a jsonable arg. Both are mandatory.
    We return the deserialized contents of executing the set of commands on the remote facility as a list of objects
    '''
    facilityConfig = toolconfig.getConfigForFacility(facility)
    # Each facility has a config element that tells us machine and use credentials. 
    ssh    = facilityConfig['ssh']
    if toolconfig.usesGateway(facility):
       gateway = facilityConfig['gateway']
       conargs=['ssh','-x', gateway,'ssh -x -o BatchMode=yes ' ,ssh,'multi_facility_process_helper.py']
    else:
       conargs=['ssh','-x',ssh,'-o BatchMode=yes','multi_facility_process_helper.py']
    try:
        proc = subprocess.Popen(conargs,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
        commandStr = json.dumps(commandsAndArgs)
        if globals.verbose:
            print "Sending to remote multi_facility_process_helper - ", commandStr, "on", facility, "with ssh =", ssh, "using", ( gateway if toolconfig.usesGateway(facility) else ' no ') , "gateway"
        
        [stdoutdata, stderrdata] = proc.communicate(commandStr)

        if globals.verbose:
            print "stderr", stderrdata
        if globals.verbose:
            print "stdout", stdoutdata
        
        if proc.returncode != 0:
           err_msg = {'name':facility,'stdout':stdoutdata,'stderr':stderrdata,'rc':proc.returncode}
           raise connectionException(err_msg) 
        ret = json.loads(stdoutdata)
        if globals.verbose:
            print "Return from multi_facility_process_helper", ret
        return ret
    except subprocess.CalledProcessError:
        return ""



class connectionException(Exception):
      pass
