#!/bin/bash
# sms sender parameters
# $1 - phone number $2 - text message content
#
# dependencies : openssl, python, curl
########################################################

PHONE_NUMBER=`echo $1 |  tr -d ' +.'` #remove plus, spaces and dots
TEXTMESSAGE=$2

#URL=https://kavremote.mobil.cz:443/smsgateway.pl 
URL=https://api.klikniavolej.cz:443/smsgateway.pl
#LOGTEMPFILE=$(mktemp /tmp/smslog.XXXXXXXXXX) || { echo "Failed to create temp logfile"; exit 1; }
LOGFILE=/tmp/fred_sms_klikniavolej.log
BLACKLIST=/etc/fred/sms_send_blacklist.conf

# Get LOGIN, PASSWORD and SENDER
source /etc/fred/sms_send_klikniavolej.conf

echo "-=-=-=-=-=-=-=-= $(date) =-=-=-=-=-=-=-=-" >> $LOGFILE
echo "ARGS" >> $LOGFILE
echo "$@" >> $LOGFILE

if [ -r $BLACKLIST ]; then
    if [ "$(grep $PHONE_NUMBER $BLACKLIST)"x == "$PHONE_NUMBER"x ]; then
        echo $'\n'"$PHONE_NUMBER found in blacklist - not sending" >> $LOGFILE
        exit 2;
    fi
fi

# prepare request data
TEXTMESSAGE2=$(python -c "import urllib; print urllib.quote('$TEXTMESSAGE');")

REQUEST_DATA=" -d login=$LOGIN -d password=$PASSWORD -d number=${PHONE_NUMBER} -d text=$TEXTMESSAGE2 -d sender=$SENDER -d encoding=ascii"

# log and process request
echo "QUERY" >> $LOGFILE
echo "curl $REQUEST_DATA  $URL" | sed -e 's/-d password=[^ ]\+/-d password=****/' >> $LOGFILE
CURL_RESULT=`curl $REQUEST_DATA $URL 2>/dev/null`

echo "RESPONSE" >> $LOGFILE
echo $CURL_RESULT >> $LOGFILE
echo $CURL_RESULT | grep -e "^OK;" >/dev/null && exit 0
exit  1
