#!/bin/bash
set  -e

usage()
{
cat << EOF
usage: $0 options

This script will collect a screenshot from a cisco sccp phone and save it to a png file.

OPTIONS:
   -h      Show this message
   -i	   Ip-Address of the phone to pull the screenshot from
   -u      Phone Username	(also requires password)
   -p      Phone Password
   -f	   Output File		(without an extension, defaults to screenshot)
EOF
}

IPADDRESS=
OUTPUTFILE=screenshot
USERNAME=
PASSWORD=
while getopts “h:i:u:p:f:?” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         i)
             IPADDRESS=$OPTARG
             ;;
         u)
             USERNAME=$OPTARG
             ;;
         p)
             PASSWORD=$OPTARG
             ;;
         f)
             OUTPUTFILE=$OPTARG
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $IPADDRESS ]] || [[ -z $OUTPUTFILE ]]
then
     usage
     exit 1
fi

screenshot_tmp=$(mktemp)
echo "Retrieving Screenshot from phone at $IPADDRESS..."
if [[ ! -z $USERNAME ]]; then
	if [[ ! -z $PASSWORD ]]; then
		wget -q --user $USERNAME --password $PASSWORD --progress=dot http://$IPADDRESS/CGI/Screenshot -O $screenshot_tmp>/dev/null
	else 
		usage
		exit 1
	fi
else
	wget -q http://$IPADDRESS/CGI/Screenshot -O $screenshot_tmp>/dev/null
fi
if [ -z "`grep 'CiscoIPPhoneError' $screenshot_tmp`" ]; then
        cat $screenshot_tmp
        echo "1 = Error Parsing CiscoIPPhoneExecute object"
        echo "2 = Error framing CiscoIPPhoneResponse object"
        echo "3 = Internal file error"
        echo "4 = Authentication error"
        rm $screenshot_tmp
        exit 1
fi

#echo "Retrieving ModelInfo from phone at $IPADDRESS..."
deviceinfo_tmp=$(mktemp)
wget -q http://$IPADDRESS/DeviceInformationX -O $deviceinfo_tmp>/dev/null
modelnumber=`grep modelNumber $deviceinfo_tmp`
if [[ ! -z "`grep -e 7960 -e 7940 DeviceInformationX`" ]]; then
	echo "Converting Screenshot to ${OUTPUTFILE}.png..."
	$0/../scr2img $screenshot_tmp $OUTPUTFILE.png
elif [[ ! -z "`grep -e 8941 -e 8945 DeviceInformationX`" ]]; then
	echo "Saving Screenshot to ${OUTPUTFILE}.png..."
	mv $screenshot_tmp ${OUTPUTFILE}.png
else
	if [ -n "`which bmptopnm`" ]; then
		echo "Saving Screenshot to $OUTPUTFILE.png..."
		bmptopnm $screenshot_tmp 2>/dev/null|pnmtopng - >${OUTPUTFILE}.png 2>/dev/null
	else
		echo "Saving Screenshot to $OUTPUTFILE.bmp..."
		mv $screenshot_tmp ${OUTPUTFILE}.bmp
	fi     
fi
[ -f $screenshot_tmp ] && rm $screenshot_tmp >& /dev/null
[ -f $deviceinfo_tmp ] && rm $deviceinfo_tmp >& /dev/null


