#!/usr/bin/env python

#
# This file is part of phantom_scheduler.
#
# phantom_scheduler is free software: you can redistribute it and/or modify
# it under the terms of the LGNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# phantom_scheduler is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# LGNU Lesser General Public License for more details.
#
# You should have received a copy of the LGNU Lesser General Public License
# along with phantom_scheduler.  If not, see <http://www.gnu.org/licenses/>.
#
# DTU UQ Library
# Copyright (C) 2014 The Technical University of Denmark
# Scientific Computing Section
# Department of Applied Mathematics and Computer Science
#
# Author: Daniele Bigoni
#

__all__ = []

import os
import sys
import socket
import getopt
import subprocess

def main(argv):
    # Get arguments
    try:
        opts, args = getopt.getopt(argv,"h:p:",["hostname=","port="])
    except getopt.GetoptError:
        print 'test.py -h <hostname> -p <port>'
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h','--hostname'):
            HOST = arg
        elif opt in ("-p", "--port"):
            PORT = int(arg)
    
    # Prepare socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect( (HOST,PORT) )
    
    while True:
        job = s.recv(1024)
        if job == 'EXIT': break
        # Execute job
        child = subprocess.Popen(job, shell=True)
        returncode = child.wait()
        # Report on done
        s.sendall(str(returncode))

    s.close()

if __name__ == "__main__":
    main(sys.argv[1:])
