#!/bin/sh


. "$(dirname "$0")/common"

if [ ! -z "$SYNOPKG_PKGDEST" -a -z "$SYNOPKG_DSM_VERSION_MAJOR" ];then
	# From UI. We need to do this. So we will not run the start script
	# at boot time when the package is disabled.
	# When the package is enabled, we would like to run the start script.
	# So we can correct the httpd.conf after DS firmware upgrade
	# The version 731 does not touch the file enabled for us. So we have to
	# do it our self.
	case "$1" in
		start)
			touch $WebalizerEnabled;
			;;
		stop)
			rm -f $WebalizerEnabled
			;;
	esac
fi

case "$1" in
	start)
		if [ ! -f "$WebalizerEnabled" -a -z "$SYNOPKG_DSM_VERSION_MAJOR" ]; then
			exit;
		fi

		# Change default backend to apache
		cp -rf $WebalizerTarget/synology_added/$WebConfig $WebConfigDir/$WebConfig

		if [ ! -f "$AccessLogDir/user-access_log" -o ! -s "$AccessLogDir/user-access_log" ]; then
			# To generate the first record. So the webalizer can create the first data
			/bin/wget -Y off --spider http://127.0.0.1:914/ > /dev/null 2>&1
		fi
		
		# Execute the webalizer once. So we will have data before crontab run it.
		$WebalizerBin -c $WebalizerConf

		# Put the webalizer to crontab
		/bin/grep $CronJob /etc/crontab > /dev/null 2>&1
		if [ $? != 0 ]; then
			echo "13	*	*	*	*	root	$CronJob" >> /etc/crontab
			kill -1 `cat /var/run/crond.pid`
		fi

		# Enable desktop icon
		rm -f $WebalizerUIDir
		if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
			ln -sf ${WebalizerUI} $WebalizerUIDir
			${DSM_INDEX_ADD} ${WebalizerUI}/index.conf
		else
			ln -sf ${WebalizerTarget}/desktop $WebalizerUIDir
		fi
		;;
	stop)
		if [ -f "$WebalizerEnabled" -a -z "$SYNOPKG_DSM_VERSION_MAJOR" ]; then
			exit;
		fi
		# Remove webalizer from crontab
		/bin/grep $CronJob /etc/crontab > /dev/null 2>&1
		if [ $? = 0 ]; then
			/bin/grep -v $CronJob /etc/crontab > /etc/crontab.tmp
			/bin/mv /etc/crontab.tmp /etc/crontab
			kill -1 `cat /var/run/crond.pid`
		fi

		# Disable desktop icon
		if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
			${DSM_INDEX_DEL} ${WebalizerUI}/index.conf
		fi
		if [ -d "$WebalizerUIDir" ]; then
			rm -rf $WebalizerUIDir
		fi
		# Remove Nginx config
		rm -rf $WebConfigDir/$WebConfig

		;;
	status)
		/bin/grep $CronJob /etc/crontab > /dev/null 2>&1
		if [ $? = 0 ]; then
			exit 0;
		fi
		exit 1
		;;
	log)
		echo $WebalizerLog
		;;
	*)
		echo "Usage: $0 {start|stop|status|log}" >&2
		exit 1
		;;
esac

exit 0
