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

# TODO: Check errors
HOST = os.environ["SERVER_IP"]
PORT = int(os.environ["SERVER_PORT"])
LISTEN_CONNECTIONS = int(os.environ["SERVER_LISTEN_CONNECTIONS"])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('[SERVER] Socket created')

#Bind socket to local host and port
try:
	s.bind((HOST, PORT))
except socket.error as msg:
	print('[SERVER] Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
	sys.exit()
	
print('[SERVER] Socket bind complete')

#Start listening on socket
s.listen(LISTEN_CONNECTIONS)
print('[SERVER] Socket now listening')

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
	conn, addr = s.accept()
	print('[SERVER] Connected with ' + addr[0] + ':' + str(addr[1]))
	
s.close()