#!/bin/sh

NPLIST="np_list"
TEMPLATE="template.ds"
WORKDIR="wrk"

die() {
	echo $@
	exit 1
}

[ -r ${TEMPLATE} ] || die "Wrong template ${TEMPLATE}"
[ -r ${NPLIST} ] || die "Unable to read list of systems' sizes from ${NPLIST}"

for d in `cat ${NPLIST}`; do
	TASK_SUBDIR="$(printf "%05u" $d)"
	TASK_DIR="${WORKDIR}/${TASK_SUBDIR}"
	TASK_NAME="ps${TASK_SUBDIR}.ds"
	mkdir -p ${TASK_DIR} || die "Unable to create output directory ${TASK_DIR}"
	cat ${TEMPLATE} | sed	-e "s/num_particles/$d/" -e "s/system_name/ps${TASK_SUBDIR}/" > "${TASK_DIR}/${TASK_NAME}"
	echo "Made ${TASK_NAME} in ${TASK_DIR} (num_particles $d)"
# Under FreeBSD, there is daemon(8). Under Linux, things are complicated.
# With Gentoo's OpenRC we get start-stop-daemon.
# "User-friendly" Linux distributions sucks. We have to do the spawning in portable way.
	pushd "${TASK_DIR}" > /dev/null
	psmod "${TASK_NAME}" > /dev/null 2>&1 &
	PID="$!"
	echo $PID > $(echo ${TASK_NAME} | sed -e 's/\.ds/\.pid/')
	popd > /dev/null
done

