#!/bin/bash
usage()
{
   /usr/bin/gettext -e "usage: $cmd --help\n"
   /usr/bin/gettext -e "       $cmd { -o c | v | r } -f file-name\n"
   /usr/bin/gettext -e "\n"
   /usr/bin/gettext -e "          -o - type of operation, c for capturing screen, v for\n"
   /usr/bin/gettext -e "               viewing a captured screen, or r to remove file(s)\n"
   /usr/bin/gettext -e "               created by this program.\n"
   /usr/bin/gettext -e "          -f - Name of the file to copy or read the screen\n"
   /usr/bin/gettext -e "               capture. Do not specify the path name, file will\n"
   /usr/bin/gettext "               be read from or created under \$HOME/.screen_capture"
   /usr/bin/gettext -e "\n"
   /usr/bin/gettext "               directory."
   /usr/bin/gettext -e "\n"
   /usr/bin/gettext -e "\n"
   /usr/bin/gettext -e "When using the view option, left mouse click on the displayed\n"
   /usr/bin/gettext -e "screen to dismiss it, or hit ctrl-c.\n"
   exit 0
}

cmd=`basename $0`
HOSTNAME=/bin/hostname
export TEXTDOMAIN=scripts

#
# check if the person is remotely logged in, set DISPLAY if yes
#
LOG_PTS=`/usr/bin/tty | sed 's@/dev/@@'`

LOG_HOST=`who | grep "$LOG_PTS " | grep "(" | cut -f2 -d '(' | cut -f1 -d')' | cut -f1 -d':'`
if [[ -n $LOG_HOST && -z $DISPLAY ]]; then
 export DISPLAY=$LOG_HOST:0
fi


if [[ -z $DISPLAY ]]; then
 # if no value is set, use DISPLAY for regular mode, and do
 # not use hostname b/c its faster
 export DISPLAY=":0.0"
fi

soption=""
ofile=""

set -- `getopt -u -l help "o:f:" $*`
while [ "$1" != "--" ]
do
   case $1 in
        "-o")
	    soption="$2"
	    shift;
	    shift;
	    ;;
	"-f")
	    ofile="$2"
	    shift;
	    shift;
	    ;;
	"--help")
	    usage
	    ;;
	*)
	    usage
	    ;;            
   esac
done
if [ "$ofile" == "" ]
then
   usage
fi
if [ "$soption" == "" ]
then
   usage
fi
if [ "$soption" != "c" -a "$soption" != "v" -a "$soption" != "r" ]
then
   usage
fi
x=`/usr/bin/dirname $ofile`
if [ "$x" != "." ]
then
   usage
fi

# Now we can do the work
if [ ! -d $HOME/.screen_capture ]
then
   /bin/mkdir $HOME/.screen_capture
fi
BASEDIR_NAME=$HOME/.screen_capture
case $soption in
   "c" )
       /usr/X11R6/bin/xwd -frame -out $BASEDIR_NAME/$ofile
       rc=$?
       if [ $rc -eq 0 ]
       then
         echo "Screen captured in file : $BASEDIR_NAME/$ofile"
       else
         echo "Failed to capture screen"
         exit $rc
       fi
       ;;
   "v" )
       /usr/X11R6/bin/xwud -in $BASEDIR_NAME/$ofile
       ;;
   "r" )
       /bin/rm $BASEDIR_NAME/$ofile
       ;;
esac
exit $?
