#!/bin/bash
# Number of jobs
JOBS=3
# Maximal running jobs
MAXJOBS=999
# Input files
FILES="HelloWorld.c HelloWorld.jdl HelloWorld.sh"
# End of line
END="\r\t\t\t\t\t\t\t\t"
# Define colors
COLOR_NORMAL="\033[0m"
COLOR_GREEN="\033[32m"
COLOR_RED="\033[31m"

# Line subroutine
line()
{
	echo -e "--------------------------------------------------------------------------"
}

# OK message subroutine
message_ok()
{
	echo -ne "$END$COLOR_GREEN[   OK   ]$COLOR_NORMAL\n"
}

# FAILED message subroutine
message_failed()
{
	echo -ne "$END$COLOR_RED[ FAILED ]$COLOR_NORMAL\n"
}

# Subroutine for making directory
make_dir()
{
	echo -ne "Make folder: job_$1"
	if (mkdir job_$1) then
               message_ok;
        else
               message_failed;
        fi
}

# Subroutine for copying files
copy_files()
{
	echo -ne "Copy files... "
	if (cp $FILES job_$1) then
               message_ok;
        else
               message_failed;
        fi
}

# Subroutine for chainging text in files (where needed)
change_value()
{
	echo -ne "Change value: HelloWorld.c"
	mv job_$1/HelloWorld.c job_$1/HelloWorld.temp
	if (sed '/Hello World/s//Hello World from 'job$1'/g' job_$1/HelloWorld.temp >> job_$1/HelloWorld.c) then
                message_ok;
        else
                message_failed;
        fi
	rm -r job_$1/HelloWorld.temp
}

# Main program
clear
for ((i=1 ; i<=$JOBS ; i++))
do
	# Creating same lenght string numbers
	nummax=`echo $MAXJOBS | wc -c`
	numcounter=`echo $i | wc -c`
	numzero=`expr $nummax - $numcounter`
	JOB=""
	for ((j=0 ; j<$numzero ; j++))
	do
		JOB=`echo $JOB"0"`
	done
	JOB=`echo $JOB$i`

	echo -e "Make $JOB job files"
	line;
	make_dir $JOB;
	copy_files $JOB;

	change_value $JOB;
	line;
done
echo -en "$COLOR_NORMAL"
