#!/usr/bin/env python3
# Simple finger client -- uses basic socket operations

import sys
from socket import * # So I don't have to prefix with "socket"
import string
FINGERPORT = 2079 # standard port for finger is 79

def finger(user, machine, port=FINGERPORT):
    # create a socket and connect to port on machine
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((machine, port))

    # message to send is username followed by end of line, encoded as bytes
    mess = (user+"\r\n").encode()

    # keep sending until entire message is sent
    totalsent = 0
    while totalsent < len(mess):
        totalsent += s.send(mess[totalsent:])

    # collect data until server closes the connection
    # Note: This _should_ have some size limit.
    alldata = [] # This will be a list of chunks received
    while True:
       data = s.recv(1024)
       if len(data) == 0: break 
       alldata.append(data.decode())
    s.close()

    # Concatenate all of the chunks together.
    return "".join(alldata)

def main():
    try:
        user_machine = sys.argv[1]
        user, machine = user_machine.split("@")
        if len(sys.argv)>2:
           port = int(sys.argv[2])
        else:
           port = FINGERPORT
    except Exception as e:
        print(e)
        print("Usage: finger.py user@machine [port_number]")
        raise SystemExit

    print(finger(user, machine, port))

if __name__=="__main__": main()
