#!/bin/bash
#
# recordum_ip_nc
#
# v0.1 2017-11-03 RE
#
# netcat port scanner to test for available TCP/UDP ports

MYSELF=$( basename $0 )
TIMESTAMP=$( date +%Y%m%d-%H%M%S )

# helper
script_help() {
    cat <<EOF
${MYSELF} help:

This script test for available TCP/UDP ports.

Usage: ${MYSELF} -h <host> -p <port> [ -M <MODE> ]

where:
    <host> ... numeric IP (v4) or FQDN
    <port> ... port to connect to
    <MODE> ... mode to use TCP (default) or UDP

EOF
}

if [[ $# -lt 2 ]]
then
    script_help
    exit 1
fi

while getopts "h:p:M:" option
do
    case ${option} in
        h) HOST=$OPTARG
            ;;
        p) PORT=$OPTARG
            ;;
        M) MODE=$OPTARG
            ;;
        *) script_help
            exit 2
            ;;
    esac
done

# set defaults
if [[ -z "$HOST" ]]
then
    HOST="portal-eu.recordum.net"
fi
if [[ -z "$MODE" ]]
then
    MODE="TCP"
fi
if [[ -z "$PORT" ]]
then
    if [[ "$MODE" == "UDP" ]]
    then
        PORT=1194
    else
        PORT=80
    fi
fi
# set internal options
# wait time
WAIT=3

# trigger a tcp/udp connect
if [[ "$MODE" == "TCP" ]] # default to test for Web Access
then
    nc -z -v -w ${WAIT} ${HOST} ${PORT}
fi
if [[ "$MODE" == "UDP" ]] # UDP to test for OpenVPN
then
    nc -z -v -w ${WAIT} -u ${HOST} ${PORT}
fi

# full success
exit 0
