#!/usr/bin/env python
# This python script generates several jobscripts based on the input parameters in the 
# parameter file (params.list).Following 4 files are required to run this script.
# 1. script_gen.py
# 2. pyratemp.py
# 3. params.list
# 4. <something>.template (A template file that you will have to write) eg quelia.template or juropa.template already exist on the repository.
#
# The following steps should be followed to run this script
# Step1:
#   Create a Template file named <something>.template
#      - The template should be modified with the variables "${NPROCS}$";${PATH_TO_EXECUTABLE}$;
#        and ${ARGUMENT}$ at appropriate places in the template. See "quelia.template" for example.
# Step2:
#   Set all the Parameters in the file called params.list.
# Step3:
#   Run the script : ./script_gen.py
#
#################################################################################################################

import re
import logging
from subprocess import call
import pyratemp as pyratemp

#Read parameters from params.list
param_file = open("params.list", "r")
param_list = param_file.read()
param_file.close()


# Read the Number of processes list
line_procs = re.findall(r"NPROCS.*$", param_list,re.MULTILINE)
for x in line_procs:
  proc_temp = re.split(r"= ", x)
  list_proc = re.split(r"\s", proc_temp[1])
#  print list_proc 

# Read the argument of the code
line_argument = re.findall(r"ARGUMENT =.*$",param_list,re.MULTILINE)
for x in line_argument:
  argument_temp = re.split(r"= ",x)
  list_argument = re.split(r"\s",argument_temp[1])
#  print list_argument

# Read path to executable
line_path = re.findall(r"PATH_TO_EXECUTABLE =.*$",param_list,re.MULTILINE)
for x in line_path:
  path_temp = re.split(r"= ",x)
  list_path = re.split(r"\s",path_temp[1])
#  print list_path
    
# Read the name of the template file
line_template = re.findall(r"JOBSCRIPT_TEMPLATE =.*$",param_list,re.MULTILINE)
for x in line_template:
  template_temp = re.split(r"= ",x)
  list_template = re.split(r"\s",template_temp[1])
  # store the name for the filemane for jobscripts
  name=list_template[0].split('.')[0]

# Read the command for submitting jobs
line_submit = re.findall(r"COMMAND =.*$",param_list,re.MULTILINE)
for x in line_submit:
  submit_temp = re.split(r"= ",x)
  list_submit = re.split(r"\s",submit_temp[1])
#  print list_submit[0]

  

# generate the jobscripts
for procs in list_proc:
   pr=int(procs)
   # find number of nodes
   if (pr<4):
     nodes=1
   else:
     nodes=int(procs)/4 
   # find nslots (nodes*ppn)
   filename = name+'_n'+procs+'.job'
   logfile=open(filename,'w')
   mytemplate = pyratemp.Template(filename=list_template[0])
   logfile.write(mytemplate(NPROCS=procs,PATH_TO_EXECUTABLE=list_path[0],ARGUMENT=list_argument[0],NSLOTS=procs,NODES=nodes))
   logfile.close()

   # submitting the job
#   call([list_submit[0], filename])      




