#!/bin/ksh
# @(#) capture.ksh 1.1 94/03/05
# syntax: capture [ outfile ]
# capture: captures current XENIX/UNIX console screen in a file
# 91/01/18 john h. dubois iii (john@armory.com)
# 92/03/17 Added '-' as special filename, and -t option.
# 92/09/27 Use awk instead of head, print, etc.; delete trailing spaces;
#          made filename be the default option;
#          trap INT & QUIT to reset echo mode
# 94/03/05 Make sure output file can be written before sending media copy seq.

unset ENV

help="$0: capture a XENIX/UNIX console screen into a file.
Syntax: $0 [-h] [-t tty] [filename]
-h prints this help.
-t specifies the tty name of the screen to capture.
The default is to capture the current screen.
If a screen other than the current screen is to be captured, it must have
no other processes reading from it, or $0 will compete with the
other processes.  This generally means that it should be disabled.
filename is the name of the file to capture the screen into.
If no filename is given, the screen will be captured into a file
called "screen" in the current directory.
A filename of '-' will cause output to go to the standard output.
A filename of '-' should only be used if the output of $0 is 
redirected or if a tty other than the current tty is givin with -t."

unset tty

while getopts ht: opt; do
    case $opt in
    h)  echo "$help"
	exit;;
    t)  [[ "$OPTARG" = @(|.|..)/* ]] && tty=$OPTARG || tty=/dev/$OPTARG;;
    esac
done

shift $((OPTIND - 1))

case $# in
0) outfile=screen;;
1) outfile=$1;;
*) echo "$help"
   exit;;
esac

set -e

exec < $tty

trap "stty echo; exit" INT QUIT

# Make sure we can write the output file before echoing media copy sequence
if [ "$outfile" != - ]; then
    exec 2> $outfile
fi

stty -echo
[ -z "$tty" ] && print -n "\033[2i" || print -n "\033[2i" > $tty
# Save output and then write it in case capture output goes to the screen
# it's reading for some silly reason
awk '
{
    sub(" +$","")
    Lines[++i] = $0
}
NR == 25 {
    for (i = 1; i <= 25; i++)
	print Lines[i]
    exit
}
' 1>&2
stty echo
