#!/usr/bin/env python

import string, sys, os, urllib
from prefs import *
# Find the installation dir of snarfzilla


keyindex = sys.stdin.readline() # Send to key index server?
keyindex = keyindex[:-1]

hops = sys.stdin.readline() # Hops to Live
hops = hops[:-1]

key = sys.stdin.readline()
key = string.strip(key)
key = (r'%s' % key)
filename = sys.stdin.readline()
filename = (r'%s' % filename)

print "Got filename", filename
if string.find(filename, ' ') != -1:
    print "ERROR - No spaces in filenames, please."
    sys.stdout.write("\n")
    sys.stdout.flush()
    sys.exit()
print "1\n"
filename = string.strip(filename)
sys.stdout.write("Begin\n")
sys.stdout.flush()
#win32
#finsert = (r"\Freenet\Finsert")

#os.system(cmd)

#i,  o, result = os.popen3('%s --htl %s %s "%s"' % (finsert, hops, key, filename))
cmd = ('%s --htl %s -s %s "%s" "%s"' % (finsert, hops, serverAddress, key, filename))
print cmd
sys.stdout.flush()
i,  o, result = os.popen3(cmd)
#result = os.popen("%s/freenet_insert --htl %s '%s' '%s' 2>&1 &" % (freenetdir, hops, key, filename))
l = result.readline()
sys.stdout.write(l)
sys.stdout.flush()
err = 1
insertgood = 0
'''
while l:
    l = result.readline()
    if string.find(l, "Inserted Key") != -1:
        insertgood = 1
    sys.stdout.write(l)
    sys.stdout.flush()
#print "Done"
#for l in result : sys.stdout.write(l)
#for l in result:
#    sys.stdout.write(l)
'''

done = 0
#for l in result:
while l:
    l = result.readline()
    if string.find(l, 'Inserted Key   : freenet:SSK@') != -1:
        key = l[17:]
        print "Public SSK: ", key
    if string.find(l, "Inserted Key") != -1:
        sys.stdout.write(l)
    if done == 0:
        s = string.find(l, "State")
        if s == 0:
            sys.stdout.write(l)
        d = string.find(l, "Data:")
	if d == 0:
	    done = 1
    else:
	sys.stdout.write(l)
#sys.stdout.write(result)

if keyindex == "1" and insertgood == 1: # Send to key index server
    url = ('http://azrael.dyn.cheapnet.net/cgi-bin/keyindex/?key=%s' % key)
    print "Submitting to Thalassocracy..."
    f = urllib.urlopen(url)
    msgout = f.read()
    sys.stdout.write(msgout)
    print "\n"

sys.stdout.flush()
