#!/bin/sh
. /etc/functions.sh

##########################################
#    SYSLOG ALERT TYPE (syslog range)
#firewall 	129 (128-135)
#vpn 		137 (136-143)
#useraccess	145 (144-151)
#wan		161 (160-167)
##########################################

UCI_CONFIG="config_notify"
SYSLOG_MAIL=/tmp/syslog_mail_copy

# 1."logread -f > $SYSLOG_MAIL &" to copy syslog for email alert 
#   start at etc/init.d/syslog
# 2.check to send syslog mail alert at one_minute_task.sh

config_clear
config_load $UCI_CONFIG
config_get syslog $1 syslog
config_get syslog_mode $1 syslog_mode
if [ "$syslog" == "disable" ];then
	return
fi
firewall=""
vpn=""
useraccess=""
wan=""
others=""

type=$(uci oget config_notify.$1.syslog_type)
for tmp_type in $type
do 
	case $tmp_type in
		"syslog_firewall")
			firewall="enable"
			;;
		"syslog_vpn")
			vpn="enable"
			;;
		"syslog_useraccess")
			useraccess="enable"
			;;
		"syslog_wan")
			wan="enable"
			;;
		"syslog_others")
			others="enable"
			;;
		*)
			;;
       esac
done
	
syslog_msg=""
if [ "$others" == "enable" ];then
	## empty value => enable   have value => disable
	firewall="^<135>|^<129>|"
	vpn="^<141>|^<137>|"
	useraccess="^<150>|^<145>|"
	wan="^<166>|^<161>|"
	for tmp_type in $type
	do 
		case $tmp_type in
			"syslog_firewall")
				firewall=""
				;;
			"syslog_vpn")
				vpn=""
				;;
			"syslog_useraccess")
				useraccess=""
				;;
			"syslog_wan")
				wan=""
				;;
			*)
				;;
		esac
	done
	
	# "DUMMY" is to prevent grep ""	
	if [ "$syslog_mode" == "alert" ];then
		syslog_msg=`cat $SYSLOG_MAIL | grep -E -v "${firewall:-^<135>|}${vpn:-^<141>|}${useraccess:-^<150>|}${wan:-^<166>|}^DUMMY"`
	else
		syslog_msg=`cat $SYSLOG_MAIL | grep -E -v "${firewall:+^<135>|^<129>|}${vpn:+^<141>|^<137>|}${useraccess:+^<150>|^<145>|}${wan:+^<166>|^<161>|}^DUMMY"`
	fi
else
	if [ "$syslog_mode" == "alert" ];then
		syslog_msg=`cat $SYSLOG_MAIL | grep -E "${firewall:+^<129>|}${vpn:+^<137>|}${useraccess:+^<145>|}${wan:+^<161>|}^DUMMY"`
	else
		syslog_msg=`cat $SYSLOG_MAIL | grep -E "${firewall:+^<135>|^<129>|}${vpn:+^<141>|^<137>|}${useraccess:+^<150>|^<145>|}${wan:+^<166>|^<161>|}^DUMMY"`
	fi
fi

if [ "$syslog_msg" == "" ];then
	return
fi

#write mail content
file_name=$(date +%s)
type=`echo $type | sed 's/syslog_//g'`
echo "$syslog_msg" > /tmp/mail_alert/$file_name
cd /tmp/mail_alert/
tar -zcvf /tmp/mail_alert/$file_name.tar.gz $file_name
echo -e "TYPE: $type   MODE: $syslog_mode\n" > /tmp/mail_alert/$file_name

#call for send
sh /sbin/MailSendAlert.sh "99" "$file_name" >/dev/console

