#!/bin/sh
PGNAME="alarmtweet_messageonly"
PGDESC="Send alarm tweets with messages only via Twitter"
MSGTRIGGER="/tmp/$PGNAME-$$-1.tmp"
TIMEOUT=10
DEBUGLOGFILE="/usr/ns/log/alarmtweet_messageonly_debug.log"

usage () {
	echo "$PGNAME: $PGDESC"
	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

# Get the alarm id and alarm action id numbers from command line args
alarmid=$1
actionid=$2
triggerid=$3
pointid=$4
alarmtime=$5
AlarmValue=$6
interval=$7
triggertime=$8
reset=${9:-""}
test=${10:-""}

# Quit if not provided.
if [ -z "$actionid" ]; then exit 0; fi

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

# Log a timestamp to debug log file
echo $(nstime) $0 $* >>$DEBUGLOGFILE

# Check if novastar database password saved.
nsdbpassword

# Get replication parameters
# This sets things like NSREPLICATION_STATE below
eval $(nsdbrep show parameters)

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

# Get the alarm message display parameters from database.
triggerMessage=$(echo "select trigger_message from alarm where id=$alarmid" | $PSQL -qtA);
echo "triggerMessage=$triggerMessage" >> $DEBUGLOGFILE

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

# Log alarm details.
echo "AlarmState=$AlarmState" >>$DEBUGLOGFILE
echo "ALARM_ID=$alarmid" >>$DEBUGLOGFILE

# Use sed to clean up the alarm message
AlarmMsgCleanedUp=$(echo "$triggerMessage" | tr ',' ' ' | \
sed \
-e "s|  *| |g")
echo "AlarmMsgCleanedUp=$AlarmMsgCleanedUp" >>$DEBUGLOGFILE

# Prefix alarm message with test if flagged.
if [ "$test" = "-test" ]; then
	AlarmMsgCleanedUp="TEST $AlarmMsgCleanedUp"
fi

# Use sed to encode some special characters
tweet=$(echo $AlarmMsgCleanedUp | sed -e "s/ /%20/g")
tweet=$(echo $tweet | sed -e "s/#/%23/g")
echo encoded tweet: $tweet >> $DEBUGLOGFILE
# Send Message to Twitter PHP Script
#curl  http://novastar-main.co.hays.tx.us/apps/twitter/index.php?m=$tweet

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