#!/usr/bin/env python3
import sys
import os
import glob

try:
    """ TIPC C-API library path searching """
    dir_name = os.path.dirname(os.path.abspath(__file__))
    pylib_path = glob.glob('%s%s'%(dir_name,'/../../../pytipc/build/lib*'))[0]
    sys.path.append(pylib_path)
except:
    pass

from tipc import *

SERVER_TYPE = 18888
SERVER_INST = 17
BUF_SIZE = 40

def pyapi_hello_world_server():
    print("****** TIPC hello world server started ******")
    s = TipcConn(SOCK_RDM)
    if s.bind(SERVER_TYPE, SERVER_INST, SERVER_INST) != 0:
        print("Server: failed to bind port name\n")
        sys.exit(0)

    ret, msg, memberid, socketid, err = s.recvfrom(BUF_SIZE)
    if ret <= 0:
        print >> sys.stderr, "Server: unexpected message"
        sys.exit(0)

    print("Server: Message received: %s" %msg.decode('utf-8'))
    outbuf = "Uh ?"
    if s.sendto(outbuf, memberid) <= 0:
        print("Server: failed to send")
        sys.exit(0)

    print("Server: Sent response : %s" %outbuf)
    print("****** TIPC hello world server finished ******\n")

if __name__== "__main__":
    pyapi_hello_world_server()
