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

import sys
import socket
import getopt
import errno
import time
import phantom_scheduler as ps

def main(argv):
    # get arguments
    try:
        opts, args = getopt.getopt(argv,"hn:p:",["help=","hostname=","port="])
    except getopt.GetoptError:
        print 'Usage: psqsub -n <hostname> -p <portnum> <command>'
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h','--help'):
            print "psqsub is part of the package phantom_scheduler."
            print "This submits a job to the <hostname> listening on <port> and returns. This is non-blocking command."
            print "See psqrsh for a blocking command"
            print "Usage: psqsub -n <hostname> -p <portnum> <command>"
            sys.exit(0)
        if opt in ('-n','--hostname'):
            HOST = arg
        if opt in ('-p','--port'):
            PORT = int(arg)
    CMD = " ".join(args)
    
    while True:
        try:
            s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
            s.connect( (HOST,PORT) )
            # Declare the job not blocking
            s.sendall(ps.NON_BLOCKING)
            s.recv(1024)
            # Send the job
            s.sendall(CMD)
            s.close()
            break
        except socket.error as serr:
            if serr.errno != errno.ECONNREFUSED:
                # Not the error we are looking for, re-raise
                raise serr
            time.sleep(0.01)

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