#!/usr/bin/python

# web_file_update.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--
#       June 10, 2003           bar
#       June 13, 2003           bar     make us a subroutine
#                                       do numbered backups
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       May 27, 2012            bar     doxygen namespace
#       September 15, 2013      bar     specify the .bak base as 10
#       --eodstamps--
##      \file
#       \namespace              tzpython.web_file_update
#
#
#       Update a file or files from the web.
#
#


import  os
import  os.path
import  urllib

from    replace_file                import  replace_file


__all__     = [
                'update_file_from_web'
              ]

def update_file_from_web(url, file_name) :
    """
        Update a file from a URL.

        Return empty string if nothing was updated.
        Return "OK" if there was an update.
        Return a message of some sort if something went wrong.

        Can raise all the usual file or url operation exceptions.

        Warning!
          This thing doesn't seem to care whether the returned URL contents are valid or not. 404's will come back as ok text, for instance.
    """

    ff          = None
    if  os.path.exists(file_name) :
        ff      = open(file_name, "rb").read()

    uf          = urllib.urlopen(url).read()

    if  uf and len(uf) and (ff != uf) :

        if  not ff :        ff = ""

        if  float(len(uf)) < len(ff) * 0.9 :
            return("URL: " + url + " file is " + str(len(uf)) + " bytes long - too short to replace " + str(len(ff)) + " byte file: " + file_name)


        temp_file_name = file_name + "-tmp"
        back_file_name = file_name + "-NNNNN-bak~"

        f              = open(temp_file_name, "wb")
        f.write(uf)
        f.close()

        replace_file(file_name, temp_file_name, back_file_name, base = 10)

        return("OK")

    return("")



#
#
#
if __name__ == '__main__' :
    import  sys

    if  not (len(sys.argv) & 1) :
        print "I take URLs and file names in pairs."
        print "And replace the file with the URL's target if there has been a change to it."
        if  len(sys.argv) > 1 :
            raise "No arg"
        pass
    else :
        problem = None
        a       = 1
        while a + 1 < len(sys.argv) :

            url       = sys.argv[a]
            file_name = sys.argv[a + 1]

            r = update_file_from_web(url, file_name)
            if  r and len(r) :
                if  r == "OK" :
                    print "Updated ", file_name, "from", url
                else :
                    print     r
                    problem = r
                pass

            a = a + 2
            pass

        if  problem :   raise "Failed"

    pass


#
#
#
# eof
