#!/usr/bin/env python3
# Simple finger client -- uses sendall and makefile

import sys
from socket import * # So I don't have to prefix with "socket"

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))

    # send the user name (NOTE: sendall)
    s.sendall((user+"\r\n").encode())

    # convert socket to a file for reading
    infile = s.makefile()
    data = infile.read()  # reads everything up to socket closing

    s.close()

    return data


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()
