#!/usr/bin/env python

import sys
import sha
import optparse
from xmlrpclib import *
from pyme import core, callbacks

p = optparse.OptionParser(usage="usage: %prog [options] <key> <oldvalue> <newvalue>")
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("-k", "--keyid", dest="keyID", default="", metavar="KEYID",
                          help="the victim's OpenPGP key ID")
p.add_option("-s", "--secret", dest="secret", default="", metavar="SEC",
                          help="can be necessary if the data was stored with this secret")

(opts, args) = p.parse_args()
if (len(args) < 3):
    p.print_help()
    sys.exit(1)
if not opts.keyID:
    print "Key ID is mandatory"
    p.print_help()
    sys.exit(1)
attribute = args[0]
oldvalue = args[1]
newvalue = args[2]
ttl = 3600

proxy = ServerProxy(opts.gateway)
context = core.Context()
key_data = core.Data()
context.set_armor(False)
context.op_export(opts.keyID, False, key_data)
key_data.seek(0, 0)
pgp_key = key_data.read()
key = Binary(sha.new(pgp_key + attribute).digest())
bin_value = Binary(newvalue)
result = {0:"Success", 1:"Capacity", 2:"Again"}
if (opts.secret == ""):
    proxy.rm(key, Binary(sha.new(oldvalue).digest()), "SHA",
             Binary(opts.secret), ttl, "scramble.py")
print result[proxy.put(key, bin_value, ttl, "scramble.py")]
        

