#!/usr/bin/python

# get_file_with_ftp.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--
#       February 21, 2007       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
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.get_file_with_ftp
#
#
#       Get files using FTP.
#
#

import  ftplib
import  getpass
import  os.path
import  sys
import  time

import  replace_file



class   a_get_file_with_ftp :
    """
python  get_files_with_ftp.py  [options] file...

Options

    --user      user_name   password    Set the user name and password.
    --host      host_name               Set the host name.

    --basename  name.ext                Put 'name' in front of output file names. (e.g a path) and 'ext' after.
                                        If no 'ext' is given, take extension from remote file name.

    --datename                          Apply current YYYY_MM_DD to output file names.
    --timename                          Apply current HH_MM_SS   to output file names.

    --output    file_name               Set the absolute, local, output file name for the next file.

    """


    def __init__(me, sysargv) :

        me.host         = ""
        me.user         = ""
        me.password     = ""
        me.oname        = ""
        me.basename     = ""
        me.datename     = False
        me.timename     = False
        me.mode         = -1

        me.files        = []             # built with


        while True :
            oi  = tzlib.array_find(sysargv, [ "--user", "-u" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            me.user     = sysargv.pop(oi)
            me.password = sysargv.pop(oi)

        while True :
            oi  = tzlib.array_find(sysargv, [ "--host", "-h" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            if  not sysargv :
                print a_get_file_with_ftp.__doc__
                sys.exit(254)
            me.host     = sysargv.pop(oi)

        while True :
            oi  = tzlib.array_find(sysargv, [ "--basename", "-b" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            me.basename = sysargv.pop(oi)

        while True :
            oi  = tzlib.array_find(sysargv, [ "--datename", "-d" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            me.datename = True

        while True :
            oi  = tzlib.array_find(sysargv, [ "--timename", "-t" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            me.timename = True

        while True :
            oi  = tzlib.array_find(sysargv, [ "--mode", "-m" ] )
            if  oi < 0 :    break
            del sysargv[oi]
            me.mode     = int(eval(sysargv.pop(oi)))


        while True :
            oi  = tzlib.array_find(sysargv, [ "--help", "-h", "-?", "/?", "/h" ] )
            if  oi < 0 :    break
            print a_get_file_with_ftp.__doc__
            sys.exit(254)


        while not me.host :
            print "Host?",
            me.host     = sys.stdin.readline().strip()

        while not me.user :
            print "User?",
            me.user     = sys.stdin.readline().strip()

        while not me.password :
            me.password = getpass.getpass("Password? ")


        oname   = ""

        while len(sysargv) :
            fn  = sysargv.pop(0)

            if  (fn == '-o') or (fn == '--output') :
                oname = sysargv.pop(0)
            else :
                if  not oname :

                    t           = time.localtime()

                    if  me.datename :
                        oname  += "%04u_%02u_%02u" % ( t.tm_year, t.tm_mon, t.tm_mday )

                    if  me.timename :
                        oname  += "%02u_%02u_%02u" % ( t.tm_hour, t.tm_min, t.tm_sec )

                    rname   = os.path.split(fn)[1]
                    if  not oname :
                        oname   = rname
                        if  not oname :
                            raise "No output file name from " + rname
                        pass

                    if  me.basename :
                        (f, x)  = os.path.splitext(me.basename)
                        if  not x :
                            x   = os.path.splitext(rname)[1]
                        oname   = f + oname + x

                    pass

                me.files.append( [ fn, oname ] )

                oname   = ""
            pass

        pass



    def get_files(me) :

        if  not len(me.files) :
            raise "No files to get!"

        f   = ftplib.FTP(me.host)
        f.login(me.user, me.password)

        for (fn, oname) in me.files :

            tname   = oname + ".tmp"
            fo      = open(tname, "wb")

            f.retrbinary("RETR " + fn, lambda s : fo.write(s) )

            fo.close()

            replace_file.replace_file(oname, tname, oname + ".bak")

            if  me.mode >= 0 :
                os.chmod(oname, me.mode)

            pass
        pass


    pass    #   a_get_file_with_ftp



if  __name__ == '__main__' :

    import  tzlib
    import  TZCommandLineAtFile

    del(sys.argv[0])

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    me  = a_get_file_with_ftp(sys.argv)

    me.get_files()

    pass



#
#
#
# eof
