#!/bin/bash
#
# recordum_ip_traceroute
#
# v0.1 2017-11-03 RE
#
# print the route packets trace to network host

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

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

This script prints the route packets trace to a network host. It needs root privileges!

Usage: ${MYSELF} -h <host> [ -M <MAX HOPS> | -P <PROTOCOL> | -T <PORT> ]

where:
    <host>     ... numeric IP (v4) or FQDN (to test name resolution)
    <MAX HOPS> ... Maximum number of hops (default: 30)
    <PROTOCOL> ... UPD (default), TCP or ICMP - use different probes to bypass different firewalls
    <PORT>     ... for protocol TCP we need a target port (default: 80)

EOF
}

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

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

if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    exit 3
fi

# set defaults
if [[ -z "$HOST" ]]
then
    HOST="portal-eu.recordum.net"
fi
if [[ -z "$MAX" ]]
then
    MAX=30
fi
if [[ -z "$PROTOCOL" ]]
then
    PROTOCOL="UDP"
fi
if [[ -z "$PORT" ]]
then
    PORT=80
fi
# set internal options
# slower tracing that avoids firewall throttling
SIMULTANEOUSLY=1
# even better stability by pausing between probes, like a half second pause
PAUSE=0.5

# trigger a trace
if [[ "$PROTOCOL" == "UDP" ]] # default
then
    traceroute -N ${SIMULTANEOUSLY} -z ${PAUSE} -m ${MAX} ${HOST}
fi
if [[ "$PROTOCOL" == "ICMP" ]] # firewall workaround using ICMP ECHO
then
    traceroute -N ${SIMULTANEOUSLY} -z  ${PAUSE} -m ${MAX} -I ${HOST}
fi
if [[ "$PROTOCOL" == "TCP" ]] # firewall workaround using TCP SYN
then
    traceroute -N ${SIMULTANEOUSLY} -z  ${PAUSE} -m ${MAX} -T -p ${PORT} ${HOST}
fi

# full success
exit 0
