#!/usr/bin/env python3
import sys, os

sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))

import flashTestParser as parser

def go(startDir):

  def _delete():
    items = os.listdir(".")
    cwd = os.getcwd()
    deletedFiles = []
    notFound     = []
    for item in items:
      if os.path.isdir(item):
        os.chdir(item)
        _delete()
        os.chdir(cwd)
      elif item == "files_to_delete":
        filesToDelete = parser.fileToList(item)
        os.remove("files_to_delete")

        for fileToDelete in filesToDelete:
          if os.path.isfile(fileToDelete):
            os.remove(fileToDelete)
            deletedFiles.append(fileToDelete)
          else:
            notFound.append(fileToDelete + " (not found or not a file) ")

        deletedFiles.sort()
        notFound.sort()

        deletedFiles.extend(notFound)
        if deletedFiles:
          open("deleted_files","w").write("\n".join(deletedFiles))

  cwd = os.getcwd()
  os.chdir(startDir)
  _delete()
  os.chdir(cwd)


def usage(scriptName):
  lines = ["USAGE: %s [pathToDir]" % scriptName,
           "",
           "\"%s\" recursively searches 'pathToDir' for files called \"files_to_delete\"," % scriptName,
           "where 'pathToDir' is a path to a directory generated by FlashTest and \"files_to_delete\"",
           "is a newline-delimited list of filenames. Any files whose names appear in this list",
           "are deleted, and their filenames appended to a new file called \"deleted_files\". The",
           "original \"files_to_delete\" file will itself be deleted in all cases.",
           "",
           "Exactly which names appear in \"files_to_delete\" is determined by the Test object that",
           "originally generated the directory. See \"flashTest/lib/Tests.py\" for more details",
           ""]
  print("\n".join(lines))


if __name__ == "__main__":
  if len(sys.argv) != 2:
    usage(sys.argv[0])
  elif not os.path.isdir(sys.argv[1]):
    print("There is no directory called \"%s\"" % sys.argv[1])
  else:
    pathToDir = os.path.abspath(sys.argv[1])
    go(pathToDir)
