#!/usr/bin/env python
# fingsrv.py -- a "fake" finger server

from socket import *
import string
import sys

PORT = 2079 # Use an unprivileged port if none provided
BACKLOG = 5

# USERS is a dictionary of user names and associated data.
USERS = {
 "zelle": "John M. Zelle: Spammeister",
 "guido": "Guido VanRossum: Creator of Python, swell guy",
 "student": "A. Student: A friendly creature that means well"
}

def startServer(port):
    # create a server socket bound to PORT on this machine
    ssock = socket(AF_INET, SOCK_STREAM)
    host = gethostname() # from socket module
    ssock.bind((host, port)) # this makes it a server socket

    # Begin listening for incoming connections
    ssock.listen(BACKLOG)
    print("Server listening host:{} port:{} backlog:{}".format(host, port, BACKLOG))
    while True: # serve forever
        # Accept a connection
        csock, addr = ssock.accept()
        print("received connection from", addr)

        # Collect complete line of info from socket
        name = csock.makefile().readline()

        # Remove any whitepsace, and lookup data on user    
        name = name.strip()
        data = USERS.get(name, "No such user")

        # send repsonse and close the connection
        csock.sendall((data+"\r\n").encode("utf-8"))
        csock.close()

if __name__=="__main__":
    if len(sys.argv) > 1:
        startServer(int(sys.argv[1]))
    else:
        startServer(PORT)
