#!/usr/bin/python

import socket, sys, os

def recvlenf(conn, length, f):
    written=0
    while written < length:
        chunk = conn.recv(length-written)
        if chunk == '': raise RuntimeError,  "socket connection broken"
        written += len(chunk)
        f.write(chunk)

def recvline(conn):
    r=""
    while 1:
        s=conn.recv(1)
        if s == "\n":
            break
        r += s
    return r


cmdfn, sigfn, picfn = sys.argv[1:]

# CREATE FIFOS TO TALK TO USER

for fn in (cmdfn, sigfn):
    if os.path.exists(fn):
        os.remove(fn)
    os.mkfifo(fn)

cmdf = open(cmdfn, "r")
sigf = open(sigfn, "a")

# CREATE SOCKETS TO TALK TO PHONE

HOST = ''        # Symbolic name meaning the local host
PORT = 50007     # Arbitrary non-privileged port

n80s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
n80s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
n80s.bind((HOST, PORT))
n80s.listen(1)
n80conn, addr = n80s.accept()

print 'Connected by', addr

# AND GO

while True:
    
    # READ CMD FROM USER
    # print "Waiting for a command from a user"
    cmd = cmdf.readline()
    # print "got",cmd

    # READ PROMPT FROM PHONE
    
    # print "waiting for a command from the phone"
    data = recvline(n80conn)
    # print "got", data
    if data != "NEXT":
        print "I want next! Got: ", map(ord, data)
        break

    # SEND CMD TO PHONE
    # print "sending user cmd to the phone" 
    n80conn.sendall(cmd)
    
    if cmd == "QUIT\n": # nicer loop possible
        break

    # READ PICTURE FROM PHONE TO DISK
    
    length = int(recvline(n80conn))
    picf = file(picfn, "w")
    recvlenf(n80conn, length, picf)
    picf.close()

    # ACK USER ABOUT PICTURE
    
    sigf.write("done\n")
    sigf.flush()
    
n80conn.close()

