#!/bin/bash
#
# Uasage
# Get all CM saved logs
#
# Note:
# 1. Telnet on CM must be enabled.
# 2. The username and password are required to enter by user to access CM telnet
#

# CM IP address
SERVER='172.31.255.45'
PORT='23'

trap 'echo "Exit..."' INT

function usage()
{
	cat << EOF

getcmlogs v1.0 - Get CM logs utility

Usage: getcmlogs localfilename 'console command' [seconds]

Options:
        <seconds>       Wait receiving logs in second. default 20 seconds

Examples:
        To get all saved cm logs:

            getcmlogs cmconsole.log 'log_mirror show' 5

        To get output of "show tech" command:

            getcmlogs cmconsole.log 'show tech' 20

EOF
        exit 1
}

while getopts "h" opt; do
	case $opt in
		h|?)
			usage
			;;
	esac
done

if [ "$1" == "" ]; then
	echo ""
	echo "Missing filename and command"
	usage
fi

if [ "$2" == "" ]; then
	echo ""
	echo "Missing command"
	usage
fi

TOFILE=$1
CMD=$2
RUNSECS=20

if [ "$3" != "" ]; then
	RUNSECS=$3
fi

unset username
unset passstring
echo -n "username:"
read username
echo -n "password:"
read -s passstr

echo $'\nRunning...(press ctrl+C to exit)'

_login() {
	sleep 1
	echo "$username"
	sleep 1
	echo "$passstr"
	sleep 1
	echo $CMD
	count=$RUNSECS
	while [ "$count" -gt 0 ]; do
		count=$(($count-1))
		sleep 1
	done
}

_get_cm_logs_main() {
	_login \
	| telnet $SERVER $PORT \
	| tr "\015" "\n" \
	> $TOFILE
}

_get_cm_logs_main ${*}
