#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org

START=90
STOP=10

USE_PROCD=1
PROG=/usr/sbin/freshclam
FRESHCLAM_CONFIGFILE="/tmp/clamav/freshclam.conf"

validate_freshclam_section() {
	uci_load_validate freshclam freshclam "$1" "$2" \
		'freshclam_config_file:string' \
		'LogTime:string' \
		'LogVerbose:string' \
		'LogSyslog:string' \
		'Debug:string' \
		'LogFacility:string' \
		'Foreground:string' \
		'PidFile:string' \
		'DatabaseMirror:string' \
		'NotifyClamd:string' \
		'DatabaseOwner:string' \
		'CompressLocalDatabase:string' \
		'DatabaseDirectory:string' \
		'DNSDatabaseInfo:string' \
		'ScriptedUpdates:string' \
		'DatabaseCustomURL:string' \
		'ConnectTimeout:string' \
		'ReceiveTimeout:string' \
		'PrivateMirror:string' \
		'Checks:string' \
		'TestDatabases:string' \
		'Bytecode:string' \
		'ExtraDatabase:string' \
		'ExcludeDatabase:string'
}

start_freshclam_instance() {
	[ "$2" = 0 ] || {
		echo "validation failed"
		return 1
	}

	[ -f /tmp/freshclam.pid ] && echo "already running" && return 0

	mkdir -p "$DatabaseDirectory"
	mkdir -p /etc/clamav
	touch /tmp/freshclam.pid

	mkdir -p "$(dirname $FRESHCLAM_CONFIGFILE)"
	ln -sf "$freshclam_config_file" "$FRESHCLAM_CONFIGFILE"

	{
	echo "LogTime " "$LogTime"
	echo "LogVerbose " "$LogVerbose"
	echo "LogSyslog " "$LogSyslog"
	echo "Debug " "$Debug"
	echo "LogFacility " "$LogFacility"
	echo "Foreground " "$Foreground"
	echo "PidFile " "$PidFile"
	echo "DatabaseMirror " "$DatabaseMirror"
	echo "NotifyClamd " "$NotifyClamd"
	echo "DatabaseOwner " "$DatabaseOwner"
	echo "CompressLocalDatabase " "$CompressLocalDatabase"
	echo "DatabaseDirectory " "$DatabaseDirectory"
	echo "DNSDatabaseInfo " "$DNSDatabaseInfo"
	echo "ScriptedUpdates " "$ScriptedUpdates"
	echo "DatabaseCustomURL " "$DatabaseCustomURL"
	echo "ConnectTimeout " "$ConnectTimeout"
	echo "ReceiveTimeout " "$ReceiveTimeout"
	echo "PrivateMirror " "$PrivateMirror"
	echo "Checks " "$Checks"
	echo "TestDatabases " "$TestDatabases"
	echo "Bytecode " "$Bytecode"
	echo "ExtraDatabase " "$ExtraDatabase"
	echo "ExcludeDatabase " "$ExcludeDatabase"
	} > "$FRESHCLAM_CONFIGFILE"

	procd_open_instance
	procd_set_param command $PROG -d --config-file=$FRESHCLAM_CONFIGFILE -p /tmp/freshclam.pid --no-warnings
	procd_set_param file $FRESHCLAM_CONFIGFILE
	procd_close_instance
}

start_service()
{
	validate_freshclam_section freshclam start_freshclam_instance
}

stop_service()
{
	[ ! -f /tmp/freshclam.pid ] && echo "not running" && return 0
	PID=$(cat /tmp/freshclam.pid)
	kill "$PID"
	rm -f /tmp/freshclam.pid
}

service_triggers()
{
	procd_add_reload_trigger "freshclam"
	procd_add_validation validate_freshclam_section
}
