#!/bin/bash

printResult() {
    echo "<root>"
    echo -e "\t<code>"$1"</code>"
    echo -e "\t<X_NotificationStatus>"$2"</X_NotificationStatus>"
    echo -e "\t<X_DeviceConnectionStatus>"$3"</X_DeviceConnectionStatus>"
    echo -e "\t<X_SubscriptionStatus>"$4"</X_SubscriptionStatus>"
    echo "</root>"
}

CURL=`which curl`

if [ -z $CURL ]; then
    echo "Curl not found"
    exit 1
fi

if [ -z $1 ]; then
    echo "Url is not set"
    exit 1
fi

URL=$1

i=0
max_i=3
while [ 1 ]
    do
        if [ $i -ge $max_i ]; then
            exit 0;
        fi
        let i++

        headers=`$CURL -s --data '
<?xml version="1.0" encoding="utf-8"?>
<root>
<Value1>Zoiper</Value1>
<Value2>Incoming</Value2>
<Value3>Call</Value3>
</root>
' -D - $URL --header "Content-Type: text/xml" --header "X-NotificationClass: 4" | tr -d '\r' `


        code=`echo "$headers" | head -n 1`
        X_NotificationStatus=`echo "$headers" | grep "X-NotificationStatus" | sed 's#X-NotificationStatus: ##' | sed -e 's/^\s*//g' -e 's/\s*$//g' `
        X_DeviceConnectionStatus=`echo "$headers" | grep "X-DeviceConnectionStatus"  | sed 's#X-DeviceConnectionStatus: ##' | sed -e 's/^\s*//g' -e 's/\s*$//g' `
        X_SubscriptionStatus=`echo "$headers" | grep "X-SubscriptionStatus"  | sed 's#X-SubscriptionStatus: ##'  | sed -e 's/^\s*//g' -e 's/\s*$//g' `

        if [ "$code" != "HTTP/1.1 200 OK" ]; then
            break;
        fi

        if [ "$X_NotificationStatus" != "Suppressed" ]; then
            break;
        fi

        if [ "$X_DeviceConnectionStatus" != "Connected" ]; then
            break;
        fi

        if [ "$X_SubscriptionStatus" != "Active" ]; then
            break;
        fi

    done

printResult "$code" "$X_NotificationStatus" "$X_DeviceConnectionStatus" "$X_SubscriptionStatus" 
