#!/bin/csh -f
#
# All Rights Reserved. Copyright (C) 2004, Hitachi, Ltd.
#

if ( ( $#argv != 2 ) && ( $#argv != 1 ) ) then
  echo "usage $0:t Process-ID [Output-file]"
  goto ERROR_END;
endif

if ( ! -x "/usr/bin/gdb" ) then
  echo "Error occurred in generating core file, gdb not found."
  goto ERROR_END
endif

set CantCreateWorkDir = "Cannot create working directory on /tmp : Permission denied"
set OUTPUT = $2
set PID = $1

set WorkDir = "/tmp/javacore_ttrace.`date +%Y%m%d%H%M%S`"
while ( -e "$WorkDir" )
    set WorkDir = "/tmp/javacore_ttrace.`date +%Y%m%d%H%M%S`"
end
set MYDEVNULL = "$WorkDir/tmp_dev_null.txt"
set TMP = "$WorkDir/tmpout.txt"
mkdir "$WorkDir"
if( !( -e "$WorkDir" ) ) then
    echo "$CantCreateWorkDir"
    goto ERROR_END
endif
onintr ERROR_RMDIR

## gcoreR}hT|[gĂȂꍇ͒߂
/usr/bin/gdb -quiet -n >& $TMP << EOF
  gcore 
  quit
EOF
if ( $status != 0 ) then
  echo "Error occurred in generating core file, gdb error."
  goto ERROR_RMDIR
endif
grep "Undefined command" $TMP >& $MYDEVNULL
if ( $status == 0 ) then
  echo "Error occurred in generating core file, gdb version 5.2 or later needed."
  goto ERROR_RMDIR
endif

if ( "$2" == "" ) then
  set OUTPUT = "core.$PID"
  while ( -e "$OUTPUT" )
    set OUTPUT = "core.$PID.`date +%Y%m%d%H%M%S`"
  end
  touch "$OUTPUT" >& $MYDEVNULL
  if ( $status != 0 ) then
    echo "Cannot generate $OUTPUT file on current directory."
    goto ERROR_RMDIR
  endif
  rm -f "$OUTPUT" >& $MYDEVNULL
endif  

/usr/bin/gdb -quiet -n >& $MYDEVNULL << EOF
  attach $PID
  gcore $OUTPUT
  detach
  quit
EOF

if ( $status != 0 ) then
  echo "Error occurred in generating core file, gdb error."
  goto ERROR_RMDIR
endif

if ( -e $MYDEVNULL ) then
  rm -f $MYDEVNULL
endif
if ( -e $TMP ) then
      rm -f $TMP
endif
if ( -e $WorkDir ) then
  rmdir $WorkDir
endif

exit 0

ERROR_END:
    exit -1

ERROR_RMDIR:
    if ( -e $MYDEVNULL ) then
      rm -f $MYDEVNULL
    endif
    if ( -e $TMP ) then
      rm -f $TMP
    endif
    if ( -e $WorkDir ) then
      rmdir $WorkDir
    endif
    exit -1

