#!/usr/bin/env python
import sys
import os.path
import errno

if len(sys.argv) < 4:
    print("Usage: {0} [BATCH SCRIPT] [ARRAY SIZE] [TMP DIR]".format(sys.argv[0]))
    sys.exit(0)

chunkifier = os.path.abspath("./batch-tools/chunkify")
script_name = os.path.abspath(sys.argv[1])
array_size = int(sys.argv[2])
tmp_dir = os.path.abspath(sys.argv[3])
batch_fname = "{0}/batch.sbatch".format(tmp_dir)
prefix = "{0}/chunk".format(tmp_dir)

try:
    os.makedirs(tmp_dir)
except OSError as exc:  # Python >2.5
    if exc.errno == errno.EEXIST and os.path.isdir(tmp_dir):
        pass
    else:
        raise

s = """#!/bin/bash
#SBATCH -J array_job
#SBATCH -o {tmp_dir}/array_job_out_%A_%a.txt
#SBATCH -e {tmp_dir}/array_job_err_%A_%a.txt
#SBATCH -t 24:00:00
#SBATCH --mem-per-cpu=1000
#SBATCH --array=1-{array_size}
#SBATCH -n 1
#SBATCH -p serial
sh {prefix}-"$SLURM_ARRAY_TASK_ID".sh
""".format(array_size=array_size, prefix=prefix, tmp_dir=tmp_dir)

with open(batch_fname, 'w') as f:
	f.write(s)
#print("# Run array batch job")
#print("sbatch {0}".format(batch_fname))

