#!/bin/sh

DIFFDIR=/var/www
DIFFDIR=/var/www/ia64
DIFFDIR=/home/ftp
DIFFSEARCH=\*
DIFFSEARCH="2.5 patches cvs/*diff*"

#-----------------------------------------------------------------------#
# $Id: viewdiff,v 1.1 2003/01/16 22:42:20 bame Exp $

HEADER=false

header() {
    $HEADER && return
    echo 'content-type: text/html'
    echo
    echo "<title>$@</title>"
    echo '<div align=right><font size=-1><i><a href="http://ftp.parisc-linux.org/cgi-bin/cvslite/build-tools/viewdiff?log=y">viewdiff</a>,A quick hack by <a href=mailto:bame@hp.com>Paul Bame</a></i></font></div>'
    echo "<div align=center><b>$@</b></div>"
    HEADER=true
}

error() {
    header viewdiff ERROR
    echo "<b>$*</b>"
}

die() {
    error "$@"
    exit 0
}

showfile() {
    #header "viewdiff $QUERY_STRING $PATH_INFO"

    awk -v FILE="$QUERY_STRING" '
	BEGIN {
	    printf("content-type: text/html\n\n<pre>")
	    state = 0
	}
        (state == 0 && /^diff/ && $NF == FILE) {
	    state = 1
	    next
	}
	(state != 1) {next}
	(/^diff/) {
	    state = 2
	    exit
	}
	{
	    gsub("&", "&amp;")
	    gsub("<", "&lt;")
	    gsub(">", "&gt;")
	}
	(/^-/) {printf("<font color=red>%s</font>\n", $0); next}
	(/^\+/) {printf("<font color=blue>%s</font>\n", $0); next}
	(/^&&/) {printf("<hr noshade size=1><b>%s</b>\n", $0); next}
	{print}
	END {
	    print "</pre>"
	}
    '

    exit 0
}

index() {
    header "viewdiff $PATH_INFO"

    awk -v URI="$MYURI" '
	function diffend() {
	    if (fn != "") {
	        printf("<a target=BottomFrame href=%s?%s>%s</a> +%d -%d\n", \
			URI, fn, fn, plus, minus);
	    }
	    else {
	        print
		printf("<pre>")
	    }
	}
	function diffstart() {
	    fn = $NF
	    minus = 0
	    plus = 0
	}
        (/^diff/) {
	    diffend()
	    diffstart()
	    next
	}
	(/^---/) {next}
	(/^\+\+\+/) {next}
	(/^-/) {minus++}
	(/^\+/) {plus++}
	END {
	    diffend()
	    print "</pre>"
	}
    '
}

frameset() {
cat <<!!!
content-type: text/html

<title>viewdiff $PATH_INFO</title>

<frameset rows="30%,*">
    <frame name=TopFrame src='$MYURI?//index//'>
    <frame name=BottomFrame>
</frameset>

!!!
}

dirindex() {
    header viewdiff listing of $DIFFDIR
    echo '<pre>'
    cd $DIFFDIR
    find $DIFFSEARCH -name '*.diff*' |
	while read fname
	do
	    echo "<a target=_Top href='$MYURI/$fname'>$fname</a>"
	done
    echo '</pre>'
}

case "$PATH_INFO" in
    *../*) die '../ not allowed in diff name';;
esac

MYURI=${REQUEST_URI%\?*}	# apache extention I think
SCRIPT_URI=${MYURI%${PATH_INFO}}

DIFF=$DIFFDIR$PATH_INFO
[ -r $DIFF ] || die 'cannot read diff file'

case "$QUERY_STRING:::$PATH_INFO" in
    //index//:::?*.gz) gunzip < $DIFF | index;;
    //index//:::?*) index < $DIFF;;
    //index//:::) dirindex;;
    ?*:::*.gz) gunzip < $DIFF | showfile;;
    ?*:::?*) showfile < $DIFF;;
    :::*) frameset;;
esac
