#!/usr/bin/python

# set_xpi_hash.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       December 12, 2006       bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       November 29, 2011       bar     pyflake cleanup
#       --eodstamps--
##      \file
#
#
#       Given output from DCRC and an update.rdf file for an XPI file, put the hash(s) in the update.rdf file.
#
#

#
#
#
if __name__ == '__main__' :

    import  re
    import  sys
    import  os

    import  TZCommandLineAtFile
    import  replace_file


    del(sys.argv[0])

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


    if  len(sys.argv) == 0 :
        print "Tell me the xpi file and the update.rdf file name."
        print "I will put the hash(s) in the update.rdf file."
        sys.exit(254)

    xpi_file    = sys.argv.pop(0)

    if  len(sys.argv) > 1 :
        print "Just tell me the xpi file and the update.rdf file."
        sys.exit(253)

    rdf_file    = "update.rdf"
    if  len(sys.argv) == 1 :
        rdf_file    = sys.argv.pop(0)

    fi  = os.popen("dcrc /2 " + xpi_file, "r")
    ds  = fi.read()
    if  fi.close() != None :
        raise "Cannot run DCRC on " + xpi_file

    g   = re.search(r"\s+(\S{64})\s+" + xpi_file + "\s+\d+", ds)
    if  not g :
        print ds
        raise "Cannot find SHA256 in the DCRC output!"
    sha256  = g.group(1)

    fi  = open(rdf_file, "r")
    rdf = fi.read()
    fi.close()


    rdf = re.sub(r"<em:updateHash>sha256:([^<]+)</em:updateHash>", "<em:updateHash>sha256:" + sha256 + "</em:updateHash>", rdf)

    tfn = rdf_file + ".tmp"
    fo  = open(tfn, "w")
    fo.write(rdf)
    fo.close()

    replace_file.replace_file(rdf_file, tfn, rdf_file + ".bak")

    pass

#
#
#
# eof

