#!/bin/sh
PGNAME="alarmtweet"
PGDESC="Send alarm messages by Twitter"
MSGTRIGGER="/tmp/$PGNAME-$$-1.tmp"
MSGEMAIL="/tmp/$PGNAME-$$-2.tmp"
TIMEOUT=10
AlarmTriggerTypeNone="0"
AlarmTriggerTypeUpperLimit="1"
AlarmTriggerTypeLowerLimit="2"
AlarmTriggerTypeRiseLimit="3"
AlarmTriggerTypeFallLimit="4"
AlarmTriggerTypeNoReport="5"
AlarmTriggerTypeAtLimit="6"
AlarmTriggerTypeSystem="7"
AlarmTriggerTypeExport="8"
AlarmTriggerTypeReportCount="9"
DEBUGLOGFILE="/usr/ns/log/alarmtweetdebug.log"
usage () {
	echo "$PGNAME: $PGDESC"
	echo
	echo "Usage: $PGNAME alarmId actionId triggerId pointId alarmTime alarmValue alarmInterval triggerTime [-reset] [-test]"
}
if [ "$1" = "-h" -o "$1" = "-help" -o "$1" = "--help" ]; then
	usage
	exit 0
fi
echo $(nstime) $0 $* >>$DEBUGLOGFILE

# Check if novastar database password saved.
nsdbpassword

# Get replication parameters
eval $(nsdbrep show parameters)

# Launch point alarms on master node if replication state is slave.
if [ "$pointId" != "0" ]; then
	if [ "$NSREPLICATION_STATE" = "slave" ]; then
		echo $(nstime) ssh $NSREPLICATION_MASTERHOST $0 $* 2>&1 | tee -a $DEBUGLOGFILE
		timeout $TIMEOUT ssh $NSREPLICATION_MASTERHOST $0 $* 2>&1 | tee -a $DEBUGLOGFILE
		iret=$?
		if [ $iret -eq 0 ]; then 
			echo "$(nstime)" $0 $* "success" 2>&1 | tee -a $DEBUGLOGFILE
			exit 0
		fi
		if [ $iret -eq 124 ]; then
			echo "$(nstime) ssh $NSREPLICATION_MASTERHOST $0 TIMEOUT" 2>&1 | tee -a $DEBUGLOGFILE
		else
			echo "$(nstime) ssh $NSREPLICATION_MASTERHOST $0 completion error: $iret" 2>&1 | tee -a $DEBUGLOGFILE
		fi
		echo "$(nstime) Execute locally" 2>&1 | tee -a $DEBUGLOGFILE
	fi
fi

# Set PSQL command
PSQL="psql -d novastar -U novastar"

# Get the alarm id and alarm action id numbers.
# Quit if not provided.
alarmid=$1
actionid=$2
triggerid=$3
pointid=$4
alarmtime=$5
AlarmValue=$6
interval=$7
triggertime=$8
reset=${9:-""}
test=${10:-""}

if [ -z "$actionid" ]; then exit 0; fi
# Set log file name for alarm action.
LOGFILE=/usr/ns/log/alarmtweet.log
echo "LOGFILE=$LOGFILE" >>$DEBUGLOGFILE

# Quit if alarms disabled
alarmsdisabled=$(nsalarmsenable | grep disabled)
if [ -n "$alarmsdisabled" ]; then
	timestamp=$(date "+%m/%d/%Y %H:%M:%S");
	echo "$timestamp Alarms disabled" >>$LOGFILE
	exit 0
fi

# Get the hostname
myhostname=$(hostname);
mydomain=$(hostname -d);
system_name=$(echo "select value from configuration where name='system_name'" | $PSQL -qtA);
if [ -z "$system_name" ]; then system_name="$myhostname"; fi
if [ -z "$system_name" ]; then system_name="NovaStar5"; fi

# Get the point, station, trigger, alarm and alarm action display parameters from database.
eval $(psql novastar novastar -AtF= <<_EOF_
select 'PointIndex',id from point_view where id=$pointid;
select 'PointNumid',point_numid from point_view where id=$pointid;
select 'PointName',quote_literal(name) from point_view where id=$pointid;
select 'PointTag',quote_literal(tag_name) from point_view where id=$pointid;
select 'PointLine',line from point_view where id=$pointid;
select 'PointType',quote_literal(point_type_name) from point_view where id=$pointid;
select 'StationNumid',station_numid from point_view where id=$pointid;
select 'StationName',quote_literal(station_name) from point_view where id=$pointid;
select 'StationTag',quote_literal(station_tagname) from point_view where id=$pointid;
select 'TriggerName',quote_literal(name) from alarm_trigger where id=$triggerid;
select 'TriggerLimit',limit_value from alarm_trigger where id=$triggerid;
select 'TriggerInterval',quote_literal(interval_as_text(interval_from_seconds(limit_interval))) from alarm_trigger where id=$triggerid;
select 'TriggerId',trigtype.id from alarm_trigger trig, alarm_trigger_type trigtype where trigtype.id=trig.type_id and trig.id=$triggerid;
select 'TriggerType',quote_literal(trigtype.name) from alarm_trigger trig, alarm_trigger_type trigtype where trigtype.id=trig.type_id and trig.id=$triggerid;
select 'TriggerThreshold',threshold from alarm_trigger where id=$triggerid;
select 'TriggerWhen',quote_literal(threshold_when_as_text(threshold_type)) from alarm_trigger where id=$triggerid;
select 'TriggerTime',quote_literal(timestamp_format(trigger_time,'MM/DD/YYYY HH:MM:SS')) from alarm where id=$alarmid;
select 'AlarmCondition',quote_literal(trigger_type_as_condition(trigtype.id)) from alarm_trigger trig, alarm_trigger_type trigtype where trigtype.id=trig.type_id and trig.id=$triggerid;
select 'AlarmValueNotUsed',trigger_value from alarm where id=$alarmid;
select 'AlarmUnits',quote_literal(point_type_units_plural) from point_view where id=$pointid;
select 'AlarmUnitsShort',quote_literal(point_type_units_abbreviated) from point_view where id=$pointid;
select 'AlarmInterval',quote_literal(interval_as_text(interval_from_seconds(trigger_interval))) from alarm where id=$alarmid;
select 'AlarmIndex',id from alarm where id=$alarmid;
select 'AlarmState',quote_literal(s.name) from alarm as a, alarm_state as s where s.id=a.state_id and a.id=$alarmid;
select 'AlarmTime',quote_literal(timestamp_format(alarm_time,'MM/DD/YYYY HH:MM:SS')) from alarm where id=$alarmid;
select 'AlarmTimeOnly',quote_literal(to_char(alarm_time,'HH24:MI')) from alarm where id=$alarmid;
select 'AlarmActionOptions',quote_literal(options) from alarm_action where id=$actionid;
select 'AlarmMessage',quote_literal(trigger_message) from alarm where id=$alarmid;
_EOF_
)

# Get the alarm trigger message
TriggerMessage=$(echo "select trigger_message from alarm where id=$alarmid" | $PSQL -AtF,)
if [ -n "$TriggerMessage" ]; then
	# Save to file if not empty, then append to alarm message.
	echo "select trigger_message from alarm where id=$alarmid" | $PSQL -qtA >$MSGTRIGGER
fi
echo "MSGTRIGGER=$MSGTRIGGER" >>$DEBUGLOGFILE

# Reset command line argument override alarm state read from database.
if [ "$reset" = "-test" ]; then 
	test="$reset"
elif [ "$reset" = "-reset" ]; then 
	AlarmState="reset";
fi
echo "AlarmState=$AlarmState" >>$DEBUGLOGFILE

# Extract alarm action email options
# Commented out 2 lines below because it crashed program -SH 12/3/2014
#eval $(echo "$AlarmActionOptions" | sed -e "s/=/='/g" -e "s/$/'/g" -e "s/&/'\&/g" | tr '&' '\n')
#echo "AlarmActionOptions=$AlarmActionOptions" >>$DEBUGLOGFILE

# Set default alarm details if not defined.
if [ -z "$ALARMDETAILS" ]; then
	#ALARMDETAILS="PointNuimn,PointName,AlarmCondition,AlarmValue,AlarmUnits,AlarmInterval,AlarmState,AlarmTime";
	ALARMDETAILS="StationTag,PointName,AlarmCondition,AlarmValue,AlarmUnitsShort,AlarmTimeOnly,AlarmMessage";
fi
echo "ALARMDETAILS=$ALARMDETAILS" >>$DEBUGLOGFILE

# Set the email subject if not defined
if [ -z "$SUBJECT" ]; then
	# Encode the email subject if not defined in options
	SUBJECT="$system_name $AlarmState"
else
	# Append reset to subject
	if [ "$reset" = "-reset" ]; then
		SUBJECT=$SUBJECT" reset"
	fi	
fi
# Prefix test alarm emails with TEST in subject
if [ "$test" = "-test" ]; then
	SUBJECT="TEST "$SUBJECT
fi
echo "SUBJECT=$SUBJECT" >>$DEBUGLOGFILE

# Set the default trigger message position in alarm message if not defined.
if [ -z "$MESSAGEPOSITION" ]; then MESSAGEPOSITION="only"; fi
echo "MESSAGEPOSITION=$MESSAGEPOSITION" >>$DEBUGLOGFILE

# Encode send mail arguments if defined
SENDMAILARGS=""
if [ -n "$FROM" ]; then
	FROM=$(echo $FROM | sed -e "s/_HOSTNAME_/$myhostname/")
  SENDMAILARGS="FROM:$FROM"
fi
echo "SENDMAILARGS=$SENDMAILARGS" >>$DEBUGLOGFILE

echo "ALARM_ID=$alarmid" >>$DEBUGLOGFILE
echo "ALARM_MESSAGE=$AlarmMessage" >>$DEBUGLOGFILE

# Prefix interval and time strings
if [ -n "$AlarmInterval" ]; then AlarmInterval="in "$AlarmInterval; fi
if [ -n "$TriggerInterval" ]; then TriggerInterval="in "$TriggerInterval; fi
if [ -n "$AlarmTime" ]; then AlarmTime="at "$AlarmTime; fi
if [ -n "$AlarmTimeOnly" ]; then AlarmTimeOnly="@ "$AlarmTimeOnly; fi
if [ -n "$StationTag" ]; then StationTag="#"$StationTag; fi
if [ -n "$TriggerTime" ]; then TriggerTime="at "$TriggerTime; fi


# Blank alarm value and units for no report alarms
echo "ALARMCANDITION=$AlarmCondition" >>$DEBUGLOGFILE
if [ "$AlarmCondition" = "no report" ]; then 
	AlarmValue="";
	AlarmUnits="";
#	AlarmConditionFixed = $AlarmCondition;
#elif [ "$AlarmCondition" = "drops" ]; then
#	AlarmConditionFixed = "dropped";
#elif [ "$AlarmCondition" = "exceeds" ]; then
#	AlarmConditionFixed = "rate";cd 
#else
#	AlarmConditionFixed = "value";
fi
echo "ALARMCANDITIONFIXED=$AlarmConditionFixed" >>$DEBUGLOGFILE

# For system alarms replace point numid when alarm trigger name and blank alarm value
# For system alarms use trigger name in place of point numid
if [ "$pointid" = "0" ]; then 
	PointNumid="$TriggerName";
	AlarmValue="";
fi

echo "ALARMDETAILS=$ALARMDETAILS" >>$DEBUGLOGFILE
# Translate alarm email message replacing tokens with point, station, trigger, alarm parameters
AlarmMsg=$(echo $ALARMDETAILS | tr ',' ' ' | \
sed \
-e "s|PointIndex|$PointIndex|g" \
-e "s|PointNumid|$PointNumid|g" \
-e "s|PointName|$PointName|g" \
-e "s|PointTag|$PointTag|g" \
-e "s|PointLine|$PointLine|g" \
-e "s|PointType|$PointType|g" \
-e "s|StationNumid|$StationNumid|g" \
-e "s|StationName|$StationName|g" \
-e "s|StationTag|$StationTag|g" \
-e "s|TriggerName|$TriggerName|g" \
-e "s|TriggerLimit|$TriggerLimit|g" \
-e "s|TriggerInterval|$TriggerInterval|g" \
-e "s|TriggerId|$TriggerId|g" \
-e "s|TriggerType|$TriggerType|g" \
-e "s|TriggerThreshold|$TriggerThreshold|g" \
-e "s|TriggerWhen|$TriggerWhen|g" \
-e "s|AlarmConditionFixed|$AlarmConditionFixed|g" \
-e "s|AlarmCondition|$AlarmCondition|g" \
-e "s|AlarmValue|$AlarmValue|g" \
-e "s|AlarmUnitsShort|$AlarmUnitsShort|g" \
-e "s|AlarmUnits|$AlarmUnits|g" \
-e "s|AlarmInterval|$AlarmInterval|g" \
-e "s|AlarmIndex|$AlarmIndex|g" \
-e "s|AlarmState|$AlarmState|g" \
-e "s|AlarmTimeOnly|$AlarmTimeOnly|g" \
-e "s|AlarmTime|$AlarmTime|g" \
-e "s|AlarmMessage|$AlarmMessage|g" \
-e "s|TriggerTime|$TriggerTime|g" \
-e "s|  *| |g")
echo "AlarmMsg=$AlarmMsg" >>$DEBUGLOGFILE

# Prefix alarm message with test if flagged.
# if [ "$test" = "-test" ]; then
# 	AlarmMsg="TEST $AlarmMsg"
# fi
#echo "AlarmMsg=$AlarmMsg" >>$DEBUGLOGFILE

# Assemble alarm message and trigger message
# Display message only or message first
(
if [ "$MESSAGEPOSITION" = "only" -o "$MESSAGEPOSITION" = "before" ]; then
  if [ -s "$MSGTRIGGER" ]; then cat "$AlarmMessage"; fi
fi
if [ "$MESSAGEPOSITION" != "only" ]; then echo "$AlarmMsg" ; fi
if [ "$MESSAGEPOSITION" = "after" ]; then
  if [ -s "$MSGTRIGGER" ]; then cat "$MSGTRIGGER"; fi
fi
) >$MSGEMAIL
echo "MSGEMAIL=" >>$DEBUGLOGFILE
cat $MSGEMAIL >>$DEBUGLOGFILE
(
timestamp=$(date "+%m/%d/%Y %H:%M:%S");
echo "$timestamp Email message"
cat $MSGEMAIL
) >>$LOGFILE

# Send Message to Twitter PHP Script
#alarmmsg=$(echo $AlarmMsg | sed -e "s/ /%20/g")
#alarmmsg=$(echo $alarmmsg | sed -e "s/#/%23/g")
#echo encoded message: $alarmmsg >> $DEBUGLOGFILE
#curl  http://wetmap.wetec.us/apps/twitter/index.php?m=$alarmmsg
tweet=$(echo $AlarmMessage | sed -e "s/ /%20/g")
tweet=$(echo $tweet | sed -e "s/#/%23/g")
echo encoded message: $tweet >> $DEBUGLOGFILE
#curl  http://wetmap.wetec.us/apps/twitter/index.php?m=$tweet
curl  http://novastar-main.co.hays.tx.us/apps/twitter/index.php?m=$tweet
#curl  http://novastar-main.co.hays.tx.us/apps/twitter/index2.php?m=$tweet

# create xml status file
outfile=/tmp/status_alarmtweet_$(hostname).xml
echo '<?xml version="1.0" ?>' > $outfile
echo '<status>' >> $outfile
echo '  <data program="alarmtweet" type="alarm" process="Automated" computer="'$(hostname)'" time="'$(nstime)'" desc="'$PGDESC'" message="'$alarmmsg'" />' >> $outfile
echo '</status>' >> $outfile


# Get the action contacts
#echo "select p.contact from alarm_contact p, alarm_action_contact_xref x where p.id=x.contact_id and x.action_id=$actionid order by x.contact_order" | \
#$PSQL -qtA | \
#while read contact
#do
#echo "contact=$contact" >>$DEBUGLOGFILE
#	# Log action and send alarm message to each contact assigned to action.
#	(
#	timestamp=$(date "+%m/%d/%Y %H:%M:%S");
#	if [ -n "$SENDMAILARGS" ]; then 
#		echo "$timestamp mail -s $SUBJECT $contact -a $SENDMAILARGS"
#	else
#		echo "$timestamp mail -s $SUBJECT $contact"
#	fi
#	) >>$LOGFILE
#	# Send mail
#	cat $MSGEMAIL | \
#	if [ -n "$SENDMAILARGS" ]; then 
#		mail -s "$SUBJECT" $contact -a "$SENDMAILARGS";
#	else 
#		mail -s "$SUBJECT" $contact;
#	fi
#done
# CLeanup message file
rm -f $MSGTRIGGER
rm -f $MSGEMAIL

echo $(nstime) $0 $* "done" >>$DEBUGLOGFILE
