#!/usr/bin/python                                                                     # -*- coding: latin-1 -*-

# subvesion_backup.py
#       --copyright--                   Copyright 2008 (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 22, 2008          bar
#       April 24, 2008          bar     whack the .tmp directory
#       May 17, 2008            bar     email adr
#       April 30, 2010          bar     copy files
#       --eodstamps--
##      \file
#
#
#       Back up any subversion repositories in the given directory.
#       Put 'em in the given directory in the same sort of tree.
#
#


import  glob
import  os
import  shutil



##  Run under older Pythons
try:
    True, False
except NameError:
    True    = 1
    False   = 0



def is_svn_dir(d) :
    return((not os.path.isdir(os.path.join(d, "format"))) and os.path.isdir(os.path.join(d, "db")) and os.path.isdir(os.path.join(d, "conf")))



def do_dir(in_dir, out_dir, verbose = False) :

    if  is_svn_dir(in_dir) :

        if  verbose :
            print "doing", in_dir, out_dir

        if  not os.path.isdir(out_dir) :
            os.makedirs(out_dir)

        return(os.system('svnadmin hotcopy "' + os.path.abspath(in_dir) + '" "' + os.path.abspath(out_dir) + '"'))

    retval  = True

    if  os.path.isfile(in_dir) :
        shutil.copy(in_dir, out_dir)
    else    :
        fns = glob.glob(os.path.join(in_dir, "*"))
        for fn in fns :
            retval &= do_dir(fn, os.path.join(out_dir, os.path.basename(fn)), verbose)
        pass

    return(retval)


#
#
#       Test
#
#
if __name__ == '__main__' :

    import  sys

    import  tzlib
    import  TZCommandLineAtFile
    import  replace_file

    del(sys.argv[0])


    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    verbose = False

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--verbose", "-v" ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        verbose = True


    if  len(sys.argv) != 2 :
        raise "Tell me the subversion directory and the target directory!"

    in_dir  = sys.argv.pop(0)
    out_dir = sys.argv.pop(0)

    t_dir   = out_dir + ".tmp"

    replace_file.remove_file_or_dir(t_dir)

    do_dir(in_dir, t_dir, verbose)

    replace_file.replace_file(out_dir, t_dir, out_dir + ".bak")

#
#
#
# eof

