#! /bin/bash
#
# Copyright (c) 2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#


usage ()
{
    echo "Usage: `basename $0` [-t TIMEOUT] [-i INTERFACE] DEST"
    echo "Tests connectivity to DEST (hostname or IP). Test is done with ping/ping6."
    echo ""
    echo "Options:"
    echo "  -t TIMEOUT     how long to wait before failing - defaults to 70 seconds"
    echo "  -i INTERFACE   interface to use for ping - default is to allow ping command to select interface"
    exit 1
}

TIMEOUT=70
IFARG=""

while getopts t:i: opt; do
    case $opt in
        t)
            TIMEOUT=$OPTARG
            ;;
        i)
            INTERFACE=$OPTARG
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z $1 ]; then
    usage
fi

if [ ! -z "$INTERFACE" ]; then
    IFARG="-I $INTERFACE"
    IFMSG="over interface $INTERFACE"
fi

DEST=$1
echo "Checking connectivity to $DEST for up to $TIMEOUT seconds $IFMSG"
while [ "$SECONDS" -le "$TIMEOUT" ]; do
    ping -c 1 $IFARG $DEST > /dev/null 2>&1 || ping6 -c 1 $IFARG $DEST > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        exit 0
    fi
    sleep 1
done

exit 1