#!/bin/zsh
echo 'Unjam Netscape version 0.4 May 31 2000 (C) Erkki Seppälä'
echo 'This program is public domain.'

(which gdb &&
 which ltrace &&
 which grep &&
 which pidof ) >/dev/null || (
echo 'Cannot find gdb, ltrace, pidof or grep.'
exit 1
)

nspid=`pidof communicator-smotif.real || pidof netscape-communicator`

if [ "$nspid" = "" ]; then
  echo 'Cannot find running netscape.'
  exit 1
fi

tmpfile="/tmp/unjam-ns.$$"

ltrace -ip $nspid >& "$tmpfile" & sleep 1; kill -INT $!

length=`perl -ne 'if (/write\(.*?([0-9]+)\)/) { print $1; exit; }' < "$tmpfile"`

(
if [ "$length" = "" ]; then
  echo "Sorry, can't unjam this netscape. (It's not in a write-loop.)"
  grep SIGSEGV "$tmpfile" >/dev/null && (
    echo "However, it seems to be stuck in a SIGSEGV-loop, so I'll kill it.."
    kill -9 $nspid
  )
  exit
fi

if [ "$length" = "0" ]; then
  echo "Netscape stuck writing 0 bytes?! Not likely.."
  exit
fi

echo "Netscape is stuck writing $length bytes. Fixing.."

gdb /proc/$nspid/exe <<EOF
set height 0
attach $nspid
break write
continue
finish
set \$eax=$length
quit
EOF
)

rm -f "$tmpfile"
