#!/bin/sh

# @file poll-sip
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# Sends an OPTIONS poll over SIP to the local machine and checks the response.
# Usage: poll-sip <port>

# Grab the command-line argument.
[ $# = 1 ] || { echo "Usage: poll-sip <port>" >&2 ; exit 2 ; }
port=$1

# Grab our configuration - we just use the local IP address.
. /etc/clearwater/config

# Get a unique ID for this request, based on the uptime.
id=$(cut -d. -f1 /proc/uptime)

# For SIP, we need to wrap IPv6 addresses in square brackets.
sip_ip=$(/usr/share/clearwater/bin/bracket-ipv6-address $local_ip)

# Send the SIP message.  The nc line also includes checking the first line of the response says
# "SIP/2.0 200 OK".
#
# The -q option keeps netcat around after sending the OPTIONS to
# allow the pollee time to send a response before the connection is
# closed.
#
# We can expect OPTIONS response time to scale with target latency (because a
# high target latency allows worker threads to become tied up with slow
# requests, thereby delaying OPTIONS responses).  Set the value of -q to be
# 0.5 secs more than the target latency, rounded up (i.e. 1500000 us more,
# rounded down).
#
# Note that the -w option (the overall timeout) needs to be larger than the -q
# option - set it to the calculated -q value plus 1.
wait_time=2

if [ ! -z "$target_latency_us" ]
then
  wait_time=$(( $(($target_latency_us + 1500000)) / 1000000 ))
fi

when_nc_started=$(date --utc  --rfc-3339=ns)

nc -v -C -w $(( $wait_time + 1 )) -q $wait_time $local_ip $port <<EOF 2> /tmp/poll-sip.nc.stderr.$$ | tee /tmp/poll-sip.nc.stdout.$$ | head -1 | egrep -q "^SIP/2.0 200"
OPTIONS sip:poll-sip@$sip_ip:$port SIP/2.0
Via: SIP/2.0/TCP $sip_ip;rport;branch=z9hG4bK-$id
Max-Forwards: 2
To: <sip:poll-sip@$sip_ip:$port>
From: poll-sip <sip:poll-sip@$sip_ip>;tag=$id
Call-ID: poll-sip-$id
CSeq: $id OPTIONS
Contact: <sip:$sip_ip>
Accept: application/sdp
Content-Length: 0
User-Agent: poll-sip

EOF
rc=$?

# Check the return code and log if appropriate
if [ $rc != 0 ] ; then
  echo SIP poll failed to $sip_ip:$port with Call-ID poll-sip-$id at $when_nc_started >&2
  echo "stderr was:"                    >&2
  cat /tmp/poll-sip.nc.stderr.$$        >&2
  echo "stdout was:"                    >&2
  cat /tmp/poll-sip.nc.stdout.$$        >&2
fi
rm -f /tmp/poll-sip.nc.stderr.$$ /tmp/poll-sip.nc.stdout.$$

# Return the return code from the egrep command (0 if found, 1 if not).
exit $rc
