#!/usr/bin/env bash
# file contains hard tabs for stripping indention with <<-EOT

set -e

source cron.sh

name=$1
shift

dir="${CTRSS_DIR}/data/${name}"
script="${name}.sh"
crontab_tmp=$(mktemp)

[ "$name" ] || { echo >&2 "Missing name!"; exit 1; }

if [ -d "$dir" ]; then
	echo "Data directory already exits"
else
	echo "Creating data dir"
	mkdir "${CTRSS_DIR}/data/${name}"
fi

if [ -f "$script" ]; then
	echo "Task already exists, skipping script creation."
else
	echo "Creating task skript ${script}"
	cat >$script <<-"EOT"
	#!/usr/bin/env bash

	cd $(dirname $0)
	source cron.sh

	$CTRSS $(basename $0 .sh) true
	EOT
fi

echo "editing crontab..."

crontab_line="@daily ~/cron/${script} ${@}"

crontab -l > $crontab_tmp

if grep "$crontab_line" $crontab_tmp -q || grep "#$crontab_line" $crontab_tmp -q; then
	echo "Script already attached to crontab, skipping."
else

	echo "Your current crontab: "
	cat $crontab_tmp
	echo

	echo "Attaching a stub for your script to crontab..."

	echo >>$crontab_tmp "#$crontab_line"
	echo >>$crontab_tmp "# do not forget stamping for daily jobs (cron2rss will issue warnings otherwise)"

	if [ ${#@} -gt 0 ]; then
		echo >>$crontab_tmp "# You passed sub-arguments, do not forget to create the corressponding section in the data dir!"
		echo >>$crontab_tmp "# (if your script uses a different section per argument)"
	fi

	crontab $crontab_tmp
	rm -rf $crontab_tmp

fi

# vim: set ts=4 sw=4 noet :