#!/usr/bin/env python

import sys
import sha
import optparse
from xmlrpclib import *
from pyme import core, callbacks
from pyme.constants.sig import mode

def mypassphrase(hint, desc, prev_bad):
    return "opendht"

p = optparse.OptionParser(usage="usage: %prog [options, -s is higly recommended] <key> <value>")
p.add_option("-g", "--gateway", dest="gateway", metavar="GW",
             default="http://opendht.nyuld.net:5851/", 
             help="gateway URI, list at http://opendht.org/servers.txt")
p.add_option("-t", "--ttl", dest="ttl", default="3600", metavar="TTL", 
             type="int", help="how long (in seconds) to store the value")
p.add_option("-s", "--secret", dest="secret", default="", metavar="SEC",
             help="can be used to remove the value later")
p.add_option("-k", "--keyid", dest="keyID", default="", metavar="KEYID",
             help="your OpenPGP key ID")
p.add_option("-d", "--debug", action="store_true",
             dest="debug", help="Set debug mode")
(opts, args) = p.parse_args()
if (len(args) < 2):
    p.print_help()
    sys.exit(1)
if not opts.keyID:
    print "Key ID is mandatory"
    p.print_help()
    sys.exit(1)
attribute = args[0]
value = args[1]

key_data = core.Data()
plain = core.Data(value)
signed = core.Data()
context = core.Context()
context.set_armor(False)
context.op_export(opts.keyID, False, key_data)
key_data.seek(0, 0)
pgp_key = key_data.read()
mykey = context.get_key(fpr=opts.keyID,secret=True)
context.signers_add(mykey)
context.set_passphrase_cb(mypassphrase)
context.op_sign(plain, signed, mode.DETACH)
signed.seek(0,0)
signature = signed.read()
pxy = ServerProxy(opts.gateway, verbose=opts.debug)
result = {0:"Success", 1:"Capacity", 2:"Again"}
key = Binary(sha.new(pgp_key + attribute).digest())
key_for_sig = Binary(sha.new(pgp_key + attribute + ".SIGNATURE").digest())
bin_value = Binary(value) 
ttl = int(opts.ttl)
shash = Binary(sha.new(opts.secret).digest()) 
if (opts.secret == ""):
    print result[pxy.put(key, bin_value, ttl, "put-authentic.py")]
    print result[pxy.put(key_for_sig, Binary(signature), ttl, "put-authentic.py")]
else:
    print result[pxy.put_removable(key, bin_value, "SHA", shash, ttl, "put-authentic.py")]
    print result[pxy.put_removable(key_for_sig, Binary(signature), "SHA", shash, ttl, "put-authentic.py")]

