#!/bin/bash -e

# Created by: Spenser Reinhardt
usage() {
	cat <<EOF

Usage: $0 [options]

This script is intended to run mrtg scans against devices with non-standard ports for the Network Switch\Router Wizard in Nagios XI.

Options:
  -h	This output.
  -H	Hostname or IP to scan	(Mandatory)
  -c	Community string		(Mandatory)
  -v	Snmp version (1 or 2)	(Default: 2)
  -p	Port to use				(Default: 161)
  -s	Port speed in bits		(Default: 100000000)
  -t	Temp file location		(Default: Switch\router wizard path) Do not change unless you have been instructed to.
  -r	Interface reference		(Default: nr (interface number) Available: nr, ip, eth, descr, name, type... 
								(multiple may be used and separated by commas or -r flags))

EOF
}

## Handle cli arguments
while getopts "hv:H:c:p:s:" opt
	do
	case $opt in
		h)
			usage
			exit 0
			;;
		v)
			version="$OPTARG"
			;;
		H)
			host="$OPTARG"
			;;
		p)
			port="$$OPTARG"
			;;
		c)
			community="$OPTARG"
			;;
		s)
			speed="$OPTARG"
			;;
		t)
			temp_dir="$OPTARG"
			;;
		r)
			if [[ -z $reference ]]; then
				reference="$OPTARG"
			else
				reference+=",$OPTARG"
			fi
		?)
			usage
			exit 1
			;;
	esac
done

if [[ -z $host ]]; then
	echo You must enter a hostname or IP to scan.
	usage
	exit 1
fi
if [[ -z $community ]]; then
	echo You must enter a community string to use.
	usage
	exit 1
fi

## Set defaults if args were not provided
if [[ -z $version ]]; then
	version="2c"
fi
if [[ -z $port ]]; then
	port="161"
fi
if [[ -z $speed ]]; then
	speed="100000000"
fi
if [[ -z $temp_dir ]]; then
	temp_dir="/usr/local/nagiosxi/tmp"
fi
if [[ -z $reference ]]; then
	reference="nr"
fi

# Main logic
outfile="${temp_dir}/mrtgscan-${host}"

echo Scanning device ${host} with cfgmaker now... Please wait
/usr/bin/cfgmaker --ifref=${reference} --show-op-down --noreversedns --zero-speed=${speed} "${community}@${host}:${port}::::${version}" > "${outfile}" 2> /dev/null

echo Scan completed and saved to ${outfile}

chown apache:nagios "${outfile}"
touch "${outfile}.done"
chown apache:nagios "${outfile}.done"

echo You should be ready to run the switch and router wizard against this config file. Be sure to use the hostname ${host} and uncheck "Scan Interfaces"