#!/bin/sh

. /lib/functions.sh

LOGROTATE_FILE=/etc/logrotate.conf
LOGROTATE_TMP_FILE=/tmp/logrotate/logrotate.conf
CONF_DIR=/etc/logrotate.d

create_logrotate_file() {
	mkdir -p /tmp/logrotate
	rm -f ${LOGROTATE_TMP_FILE}
	touch ${LOGROTATE_TMP_FILE}
	echo -e "include ${CONF_DIR}" >> ${LOGROTATE_TMP_FILE}
	echo -e "" >> ${LOGROTATE_TMP_FILE}
}

handle_logrotate() {
	local section="$1"

	local enabled
	config_get enabled $section enable
	if [ "$enabled" == "0" ]; then
		return
	fi

	local file_name
	config_get file_name $section file_name
	if [ -z "$file_name" ]; then
		# no file to rotate, return
		return
	fi

	echo -e "$file_name {" >> ${LOGROTATE_TMP_FILE}
	echo -e "\tcreate" >> ${LOGROTATE_TMP_FILE}
	echo -e "\tmissingok" >> ${LOGROTATE_TMP_FILE}
	echo -e "\tnotifempty" >> ${LOGROTATE_TMP_FILE}

	local file_count
	config_get file_count $section file_count
	if [ -n "$file_count" ]; then
		echo -e "\trotate $file_count" >> ${LOGROTATE_TMP_FILE}
	fi

	local max_file_size
	config_get max_file_size $section max_file_size
	if [ -n "$max_file_size" ]; then
		echo -e "\tmaxsize $max_file_size" >> ${LOGROTATE_TMP_FILE}
	fi

	local duration
	config_get duration $section duration
	if [ -n "$duration" ]; then
		echo -e "\tminutes $duration" >> ${LOGROTATE_TMP_FILE}
	fi

	local retention
	config_get retention $section retention
	if [ -n "$retention" ]; then
		echo -e "\tmaxage $retention" >> ${LOGROTATE_TMP_FILE}
	fi

	local compression
	config_get compression $section compression
	if [ -n "$compression" ]; then
		cmd=$(echo "$compression" | awk '{print tolower($0)}')
		echo -e "\tcompress" >> ${LOGROTATE_TMP_FILE}
		echo -e "\tcompresscmd $cmd" >> ${LOGROTATE_TMP_FILE}
	fi

	echo -e "\taddextension _logrotate" >> ${LOGROTATE_TMP_FILE}
	echo -e "\tpostrotate" >> ${LOGROTATE_TMP_FILE}
	echo -e "\t\tservice logmngr restart" >> ${LOGROTATE_TMP_FILE}
	echo -e "\t\tsleep 1" >> ${LOGROTATE_TMP_FILE}
	echo -e "\tendscript" >> ${LOGROTATE_TMP_FILE}
	echo -e "}" >> ${LOGROTATE_TMP_FILE} # close the logfile section
}

apply_logrotate_file() {
	cp ${LOGROTATE_TMP_FILE} ${LOGROTATE_FILE}
}

config_cron_job() {
	# taking the liberty to configure the cron job hourly, that is, at the end
	# of each hour, check if logrotation is needed. The logrotate daemon, when
	# triggered hourly, will still honour the configure log rotation duration,
	# the only slight different being that if the minutes for log rotation
	# are configured in such a way that it falls within the hour, then the
	# log rotation will be done at the completion of hour and not before. I do
	# not think this is a drawback in the interest of keeping things simple.
	sed -i '/logrotate/d' /etc/crontabs/root
	echo "0 * * * * logrotate ${LOGROTATE_FILE}" >> /etc/crontabs/root
	/etc/init.d/cron restart
}

logrotate_init() {
	create_logrotate_file
	config_foreach handle_logrotate log_rotate
	apply_logrotate_file
	config_cron_job
}
