#!/bin/sh

alert() {
	MAIL_QUEUE=/tmp/mail_queue
	MAIL_BODY=/tmp/mail_body.$$
	MAIL_ALERT_LOG=/tmp/mail_alert.log
	
	HOST=$(uci -q get system.@system[0].hostname)
	USERNAME=$(uci -q get system.@mail-alert[0].username)
	PASSWORD=$(uci -q get system.@mail-alert[0].password)
	SERVER=$(uci -q get system.@mail-alert[0].smtpserver)
	PORT=$(uci -q get system.@mail-alert[0].smtpport)
	TO=$(uci -q get system.@mail-alert[0].mailto)
	FROM=$(uci -q get system.@mail-alert[0].mailfrom)
	current_time=$(date +"%B %d %T")
	[ "$STATUS" == "1" ] && STATUS="successfully" || STATUS="unsuccessfully"
  	
	SBJ="$HOST alert - user login messages"
	TELNET_PORT=$(uci -c /etc/config/grocx -q get vtss_fw.@basic[0].telnet_port)
	SSH_PORT=$(uci -c /etc/config/grocx -q get vtss_fw.@basic[0].ssh_port)
	if [ "$TELNET_PORT" == "" ]; then
		TELNET_PORT=23
	fi
	if [ "$SSH_PORT" == "" ]; then
		SSH_PORT=22
	fi
	
	if [ "$LOGINNAME" == "" -a "$LOGINIP" == "" ]; then
		LOGGIN_TELNET=$(netstat -nat | grep "ESTABLISHED" | grep ":$TELNET_PORT " | awk '{printf "CLIENT : "$5" --> ROUTER : "$4"  STATE : "$6"\n"}')
		LOGGIN_SSH=$(netstat -nat | grep "ESTABLISHED" | grep ":$SSH_PORT " | awk '{printf "CLIENT : "$5" --> ROUTER : "$4"  STATE : "$6"\n"}')
		echo -e "$USER login $HOST on" `date` "\n\nconnecting TELNET clients ... \n$LOGGIN_TELNET\n\nconnecting SSH host ... \n$LOGGIN_SSH " > $MAIL_QUEUE
	elif [ "$LOGINIP" == "127001" ]; then	# time to send mail alert out
		mv $MAIL_ALERT_LOG $MAIL_QUEUE 2>/dev/null
	elif [ "$LOGINNAME" == "draytek_mail_test" -a "$LOGINIP" == "2130" ]; then	# send test mail
		echo "$current_time: This is a test mail from Vigor Router." >> $MAIL_QUEUE
	else
		echo "$current_time $LOGINNAME login attempt $STATUS from $LOGINIP. [WEB]" >> $MAIL_ALERT_LOG
	fi
	
	if [ -s $MAIL_QUEUE ]; then	# check mail queue
		ps | grep sendmail | grep -v "grep" && mv $MAIL_QUEUE $MAIL_ALERT_LOG || mv $MAIL_QUEUE $MAIL_BODY	# check if sendmail busy
	fi

	if [ -s $MAIL_BODY ]; then	# ready to sendmail
		sendmail -w 30 -s "${SUBJECT:-$SBJ}" -U "$USERNAME" -P "$PASSWORD" -t "$TO" "$SERVER${PORT:+:$PORT}" "$FROM" $MAIL_BODY
		if [ $? -eq 0 ]; then
			rm $MAIL_BODY
			logger "send mail alert success."
		else
			[ -s $MAIL_ALERT_LOG ] && cat $MAIL_ALERT_LOG >> $MAIL_BODY
			mv $MAIL_BODY $MAIL_ALERT_LOG
			logger "send mail alert failed."
		fi
	fi
}

LOGINNAME=$1
LOGINIP=$2
STATUS=$3
SUBJECT=$4
STATUS=${STATUS:-1}
EN=$(uci -q get system.@mail-alert[0].enable)
FLAG=$(uci -q get system.@mail-alert[0].flag)
if [ $EN == "1" ] && [ $FLAG == "1" ]; then
	alert;
else
	exit;
fi


