#!/bin/sh -f
#-*-sh-*-
#==============================================================
#
#  Abs:   Capture a named X window into a gif file. 
#
#  Name:  import2gif
#
#  Rem:   This shell script use "import" to capture a named X window and 
#         save the image to a gif file. 
# 
#  Usage: 
#         Syntax: import2gif  DNAME 
#
#                 DNAME: directory where file is stored 
#  Side:  
#
#  Auth:  17-Feb-2004, Jingchen Zhou   (jingchen)
#  Rev:   dd-mmm-yyyy,  Whoever    (user):
#
#--------------------------------------------------------------
#
#         dd-mmm-yyyy, Whoever (user): 
#         02-Apr-2007, Jingchen Zhou (jingchen)
#         Updated for edm display
#         25-Jul-2008, Jingchen Zhou (jingchen)
#         Updated to support LCLS Summary Display running on a Sunray client
#         10-Oct-2008, Jingchen Zhou (jingchen)
#         Added -resize (the number is the size scaled down by 1.5 from the
#         actual size in the display)
#         
#============================================================== 
DNAME=$1

fname=lcls
wnm="LCLS MAP"
HNAME=lcls-prod01

if [ $# -ne 1 ]; then
    echo "Usage: $0 DNAME"
    echo "Example: $0 /tmp"  
    exit 1
fi

if [ "`hostname`" != "$HNAME" ]; then
    echo "Please login $HNAME to run $0 !"
    exit 1
fi

if [ -f /nfs/slac/g/lcls/sys/sunray/summary ]; then
    display=`cat /nfs/slac/g/lcls/sys/sunray/summary`
else
    display=`ssh lcls-daemon1 cat /usr/local/admin/sunray/summary`
fi
echo "X display: ${display}"

if [ -z "${display}" ]; then
    echo "Can't read display info in ./sunray/summary"   
    exit 1
fi

IMPORT=`which import`
if [ ! -x ${IMPORT} ]; then
    echo "Command ${IMPORT}  not found"
    exit 1
fi

#if [ ! -w ${DNAME} ]; then
#    echo "${DNAME} not writable" 
#    exit 1
#fi
cd ${DNAME}
echo "cd `pwd`"
        
wid=`xwininfo -stats -display ${display} -name "${wnm}" | grep "${wnm}" | awk ' {print $4} '`
	
if [ -z "${wid}" ]; then
    echo "X connection refused by ${display} or"
    echo "No display ${wnm} is available"   
    exit 1
fi
	    
winopt="-display ${display}"
cmdopt="-window ${wid}"    
# divided by 1.5 
size="-resize 847x657"
 
# echo $cmdopt
echo "Capturing image from ${display} ..."
 	    
$IMPORT $size $winopt $cmdopt ${fname}.gif
if [ $? -ne 0 ]; then
    echo "import to ${fname}.gif failed"
    exit 1
fi
echo "${DNAME}/${fname}.gif done!"
 
$IMPORT $size $cmdopt $winopt ${fname}.pdf
if [ $? -ne 0 ]; then
    echo "import to ${fname}.pdf failed"
    exit 1
fi
echo "${DNAME}/${fname}.pdf done!"

if [ $? -ne 0 ]; then
    echo "No image is captured" 
    exit 1
fi

exit 0










