#!/usr/bin/python2

#
# Copyright (c) 2007,2008,2009 MBARI
# MBARI Proprietary Information.  All Rights Reserved
#

# Usage:
#
# ./Tools/xmlformat/prettyMissions.py
#
# ./Tools/xmlformat/prettyMissions.py xmlformatscript xfcGenscript dir1 dir2 ...
#

import commands, filecmp, os, re, shutil, sys, tempfile

def get_immediate_subdirectories(dir):
    return [dir + "/" + name for name in os.listdir(dir)
            if os.path.isdir(os.path.join(dir, name))]

dirs  = []
files = []

if len(sys.argv) > 2:
  xmlformat = sys.argv[1]
  xfcGen    = sys.argv[2]
  for i in range(3, len(sys.argv)):
    dir = sys.argv[i]
    if not os.path.isdir(dir):
      print >> sys.stderr, "Directory %s not found!" % dir
      continue
    dirs.append(os.path.normcase(dir))
else:
  xmlformat = os.path.normcase("Tools/xmlformat/xmlformat.pl")
  xfcGen    = os.path.normcase("Tools/xmlformat/xfcGen.py")
  dirs  = get_immediate_subdirectories( "Missions" )
  dirs.insert(0,"Missions")

# make sure we have our tools we need to pretty things up
if not os.path.isfile(xmlformat) or \
   not os.path.isfile(xfcGen):
  print >> sys.stderr, "Xmlformat or xfcGen not found!"
  sys.exit(1)

# get all the xml files
rXml = re.compile(".*\.+(xml|tx)", re.I)
for dir in dirs:
  if not os.path.isdir(dir):
    print >> sys.stderr, "Directory %s not found!" % dir
    continue
  for f in os.listdir(dir):
    filename = os.path.join(dir, f)
    if os.path.isfile(filename) and rXml.search(f):
      files.append(filename)

# did we get any files?
if len(files) <= 0:
  print >> sys.stderr, "No xml files found"
  sys.exit(0)

# gen temp directory
tmpdir = tempfile.mkdtemp()

# generate the new config file
cfile = os.path.normcase("Tools/xmlformat/xmlformat.conf")
cmd = "%s > %s" % (xfcGen, cfile)
#print "Executing %s" % cmd
commands.getoutput(cmd)

# make all xml files pretty
for f in files:
  tmpfile = os.path.join(tmpdir, os.path.basename(f))
  shutil.copy(f, tmpfile)
  cmd = "%s -i --config-file=%s %s" % (xmlformat, cfile, tmpfile)
  commands.getoutput(cmd)
  if filecmp.cmp(f, tmpfile, 1):
    #print "unchanged* %s" % os.path.abspath(f)
    pass
  else:
    print "formatted %s" % os.path.abspath(f)
    shutil.copy(tmpfile, f) 
  os.remove(tmpfile)

# rem conf file and temp directory
#os.remove(cfile)
os.removedirs(tmpdir)

