#!/usr/bin/python

# set_dir_time_back_to_latest_files.py
#       --copyright--                   Copyright 2009 (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--
#       April 19, 2009          bar
#       --eodstamps--
##      \file
#
#
#       Set the given directory's (and all sub-directories) date/time to that of the latest file contained in the directory.
#
#

import  glob
import  os
import  sys
import  time

import  TZCommandLineAtFile
import  tzlib



help_str    = """
%s      directory...
I set the date/time of the given directory(s) and their sub-directories
to that of the latest file contained in them.

"""




def do_dir(s) :
    t       = 0.0
    s       = os.path.abspath(s)
    for fname in glob.glob(os.path.join(s, "*")) :
        if  os.path.isdir(fname) :
            t   = max(t, do_dir(fname))
        else :
            t   = max(t, os.path.getmtime(fname))
        pass

    if  (t > 0.0) and (t < os.path.getmtime(s)) :
        print s, time.asctime(time.localtime(t))
        os.utime(s, ( os.path.getatime(s), int(round(t)) ) )

    return(t)




#
#
#
if  __name__ == '__main__' :

    program_name    = sys.argv.pop(0)
    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--help", "-h", "-?", "/?", "/h" ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        print help_str % os.path.split(program_name)[1]
        sys.exit(254)

    if  not sys.argv :
        print help_str % os.path.split(program_name)[1]
        sys.exit(254)


    for s in sys.argv :

        if  not os.path.isdir(s) :
            print s, "is not a directory!"
            sys.exit(111)

        do_dir(s)

    pass

#
#
#
# eof

