#!/opt/sunpy3/bin/python3

import os
import sys
import socket
import sunhpc.invoke

class App(sunhpc.core.app.Application):

    def __init__(self, argv):
        sunhpc.core.app.Application.__init__(self,argv)

        self.usage_name     = 'Check Port'
        self.usage_version  = '4.2'
        self.node_name      = 'localhost'
        self.port_num       = 5901

        nodehelp = '(nodename default=%s)' % self.node_name
        porthelp = '(port number default=%d)' % (self.port_num)
        self.getopt.l.extend([ ('node=',nodehelp),('port=',porthelp) ])
        self.getopt.s.extend([('n:',nodehelp),('p:',porthelp)])

    def parseArg(self, c):
        sunhpc.core.app.Application.parseArg(self,c)

        key, val = c
        if key in ('--port'):
            self.port_num = int(val)
        elif key in ('--node'):
            self.node_name = val

    def run(self):
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        try:
            s.connect((self.node_name,self.port_num))
        except:
            print ('Port(%s) is closed' % self.port_num)
            sys.exit(1)

        print ('Port(%s) is open' % self.port_num)
        s.close()
        sys.exit(0)

app = App(sys.argv)
app.parseArgs()
app.run()
