#!/usr/bin/python
# Utility to pack files for a LS-DYNA run
# Author: Suri Bala
# Credits: Brian Wainscott

import os,sys

RELATIVE_FILES_ONLY=0
COMPRESSION_METHODS=["gzip", "bzip2", "zip"] 
NINC=0

if len(sys.argv) == 1:
  print "Usage %s main_file.k" % sys.argv[0]
  sys.exit()

MAIN_FILE=sys.argv[1]
if os.path.exists(MAIN_FILE)==0:
  print " File %s does not exist" % MAIN_FILE
  print " Exiting ...."
  sys.exit()

JOB_NAME=MAIN_FILE.split(".").pop(0)

BASE_DIR=JOB_NAME
INCLUDE_DIR=JOB_NAME+"/INCLUDES"

if os.path.exists(BASE_DIR):
   print " Director %s exists. Do you want to remove ? " % (BASE_DIR)
   ui_rmdir=raw_input("  y - remove, n - stop  :   ")
   print " Your answer is %s", ui_rmdir
   if ui_rmdir == "y":
      os.system("rm -rf "+BASE_DIR)
   else:
      sys.exit()

os.system("mkdir -p "+INCLUDE_DIR)
ofile=open(BASE_DIR+"/main.k", "w")

def process_file (NAME):
  file=open(NAME)
  for line in file:
     ofile.write(line)
     nline=line.strip("\n")
     if (len(nline)>0 and nline[0]=="*") and ( (nline[0:4]=="*inc" or nline[0:4]=="*INC") ):
         line=file.next().strip("\n")
         print "   Found include file %s " % line
         if os.path.exists(line):
               basename=line.split("/").pop()
               if os.path.exists(INCLUDE_DIR+"/"+basename): 
                 # collision
                 os.system("cp "+line+" "+INCLUDE_DIR+"/"+basename+".copy")
                 ofile.write("INCLUDES/"+basename+"copy\n")
               else:      
                 os.system("cp "+line+" "+INCLUDE_DIR)
                 ofile.write("INCLUDES/"+basename+"\n")
         process_file(line)
  return

print " Processing file %s " % (MAIN_FILE)
process_file(MAIN_FILE)

print " Compressing .... "
os.system("tar -czf "+JOB_NAME+".tar.gz "+BASE_DIR)
print " Cleaning up .... "
os.system("rm -rf "+BASE_DIR)

print " Done. The file name is "+JOB_NAME+".tar.gz"
