#! /bin/sh
# Written by oga83

# /var/www/html/v2/SMS/sendsms_huawei.sh 192.168.1.248 admin 1248abcd +33761229502 "Exemple de SMS"

# Check command line parameters
if [ "$#" -ne 5 ]; then
    printf "Syntax: %s <IP> <Username> <Password> <PhoneNumber> <Message>\n" $0
    exit 0
fi

ROUTER_IP=$1
ROUTER_USERNAME=$2
ROUTER_PASSWORD=$3
SMS_NUMBER=$4
SMS_TEXT=$5
TMP_HEADER_FILE=/tmp/headers.tmp

CURL_OPT=--silent

ProcessRouterResponseHeader()
{
	# Get token from header
	NEWTOKEN=`cat $TMP_HEADER_FILE | grep "__RequestVerificationTokenone: " | awk -F' ' '{print $2}'`
	if [ ! -z "$NEWTOKEN" ]; then TOKEN=$NEWTOKEN; fi
	NEWTOKEN=`cat $TMP_HEADER_FILE | grep "__RequestVerificationToken: " | awk -F' ' '{print $2}'`
	if [ ! -z "$NEWTOKEN" ]; then TOKEN=$NEWTOKEN; fi
	NEWSESSIONID=`cat $TMP_HEADER_FILE | grep "Set-Cookie: SessionID=" | awk -F' ' '{print $2}' | cut -b 1-138`
	if [ ! -z "$NEWSESSIONID" ]; then SESSIONID=$NEWSESSIONID; fi
echo $NEWTOKEN
}

GetRouterData() # Param1: Relative URL
{
	#echo "GET on http://$ROUTER_IP$1"
	RESPONSE=`curl $CURL_OPT --request GET http://$ROUTER_IP$1 \
       		--dump-header $TMP_HEADER_FILE \
        	-H "Cookie: $SESSIONID" -H "__RequestVerificationToken: $TOKEN" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
       		`
	ProcessRouterResponseHeader
}

GetSessionToken() # No parameters
{
	# Get SessionID and RequestVerificationToken
	GetRouterData '/api/webserver/SesTokInfo'
        SESSIONID="SessionID="`echo "$RESPONSE"| grep -oPm1 "(?<=<SesInfo>)[^<]+"`
        TOKEN=`echo "$RESPONSE"| grep -oPm1 "(?<=<TokInfo>)[^<]+"`
}

PostRouterData() # Param1: RelativeUrl, Param2: Data, Param3:bAskNewToken
{
	# Get new token if necessary
	if [ ! -z $3 ]; then
		GetSessionToken
	fi

	#echo "POST on http://$ROUTER_IP$1 :" $2
	RESPONSE=`curl $CURL_OPT --request POST http://$ROUTER_IP$1 \
	       --dump-header $TMP_HEADER_FILE \
	       -H "Cookie: $SESSIONID" -H "__RequestVerificationToken: $TOKEN" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
	       --data "$2"`
	ProcessRouterResponseHeader
}

# Get initial SessionID and RequestVerificationToken
GetSessionToken

# Login
CREDENTIALS=`printf $ROUTER_PASSWORD | sha256sum | head -c64 | base64 -w0`
CREDENTIALS=`printf "%s%s%s" $ROUTER_USERNAME $CREDENTIALS $TOKEN | sha256sum | head -c64 | base64 -w0`
DATA=`printf "<request><Username>%s</Username><Password>%s</Password><password_type>4</password_type></request>" $ROUTER_USERNAME $CREDENTIALS`
PostRouterData "/api/user/login" "$DATA"

# Send SMS
DATA="<?xml version='1.0' encoding='UTF-8'?><request><Index>-1</Index><Phones><Phone>$SMS_NUMBER</Phone></Phones><Sca></Sca><Content>$SMS_TEXT</Content><Length>${#SMS_TEXT}</Length><Reserved>1</Reserved><Date>`date +'%F %T'`</Date></request>"
PostRouterData "/api/sms/send-sms" "$DATA" 1

# Logout
PostRouterData "/api/user/logout" "<request><Logout>1</Logout></request>"
