#!/bin/bash

# @file poll-tcp.sh
#
# Copyright (C) Metaswitch Networks 2016
# 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.

# This script polls a process on the passed in port

# Grab the command-line argument.
[ $# -ge 1 ] || { echo "Usage: poll-tcp <port> [ip] (defaults to local_ip if none specified)" >&2 ; exit 2 ; }
PORT=$1
IP=$2

# Grab our configuration - we just use the local IP address if no IP address
# was specified.
. /etc/clearwater/config
[ -n "$IP" ] || IP=$local_ip

# Do the poll - connect and check for success
nc -z -v -w 2 $IP $PORT 2> /tmp/poll-tcp.sh.nc.stderr.$$ > /tmp/poll-tcp.sh.nc.stdout.$$
cat /tmp/poll-tcp.sh.nc.stderr.$$ | head -1 | egrep -q "succeeded"
rc=$?

# Check the return code and log if appropriate
if [ $rc != 0 ] ; then
  echo TCP poll failed to $IP $PORT >&2
  cat /tmp/poll-tcp.sh.nc.stderr.$$       >&2
  cat /tmp/poll-tcp.sh.nc.stdout.$$       >&2
fi
rm -f /tmp/poll-tcp.sh.nc.stderr.$$ /tmp/poll-tcp.sh.nc.stdout.$$

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

