#!/usr/bin/env python

import string, sys, os, urllib
from prefs import *
# Find the installation dir of snarfzilla
if sys.path[0] == "":
    snarfdir = "."
else:
    snarfdir = sys.path[0]

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 = key[:-1]

filename = sys.stdin.readline()
filename = filename[:-1]

sys.stdout.write("\n")
sys.stdout.flush()
#win32
finsert = (r"\Freenet\Finsert")
cmd = ("%s --htl %s -s %s %s %s" % (finsert, hops, serverAddress, key, filename))
print "CMD", cmd
os.system(cmd)
'''
#result = os.popen("%s --htl %s '%s' '%s'" % (finsert, hops, key, filename))
#result = os.popen("%s/freenet_insert --htl %s '%s' '%s' 2>&1 &" % (freenetdir, hops, key, filename))
l = result.readline()
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:
    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()
