#!/bin/sh
# Runs a panel cron job (called through the cron-<manager> link, so the manager is the link name's suffix):
# one copy per command at a time, nothing but the license fetch while the manager's license is expired, and a
# "cron" problem registered in the panel when the command fails.

if [ "$1" = "-T" ]; then
	printf '(c) vallorean.ru'
	exit 0
fi

[ $# -gt 0 ] || exit 0

workdir=${0%%/sbin/*}
manager=${0##*-}
cd "${workdir}"

if [ -f var/${manager}_lic_expired ] && [ "$*" != "sbin/mgrctl -m ${manager} license.fetch.task" ]; then
	exit 0
fi

[ -d tmp/cronlocks ] || mkdir tmp/cronlocks
lock="tmp/cronlocks/$(echo "$*" | tr '[:punct:][:space:]' '_').lock"
(
	flock -n 3 || exit 0
	output=$($* 2>&1) || sbin/mgrctl -m "${manager}" problems.register name=cron "id=$*" level=error "info=${output}"
) 3> "${lock}"
