#!/usr/bin/python3

#
# Simplified version of prettyMissions.py to work on a given file.
# Introduced to support the 'prettyMission' command in TethysL VS Code Extension,
# which is intended to facilitate comparisons while migrating XML missions to TethysL.
#
# Usage:
# ./Tools/xmlformat/prettyMission.py path/to/file.xml
#
# Minimal manual changes wrt original prettyMissions.py,
# but also migrated to Python3 via `2to3`.
#

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

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print("Usage: %s path/to/file.xml" % sys.argv[0])
    sys.exit(1)

  file = sys.argv[1]

  xmlformat = os.path.normcase("Tools/xmlformat/xmlformat.pl")
  xfcGen    = os.path.normcase("Tools/xmlformat/xfcGen.py")

  # gen temp directory
  tmpdir = tempfile.mkdtemp()

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

  tmpfile = os.path.join(tmpdir, os.path.basename(file))
  shutil.copy(file, tmpfile)
  cmd = "%s -i --config-file=%s %s" % (xmlformat, cfile, tmpfile)
  subprocess.getoutput(cmd)

  # note: ad hoc exit_code: 0 if no changes, 111 if any changes.
  if filecmp.cmp(file, tmpfile, 1):
    exit_code = 0
  else:
    print("formatted %s" % os.path.abspath(file))
    shutil.copy(tmpfile, file)
    exit_code = 111
  os.remove(tmpfile)

  os.removedirs(tmpdir)
  sys.exit(exit_code)
