#!/bin/sh
##
##  jargon -- Trivial OpenPKG Jargon File Frontend
##  Copyright (c) 2002-2003 Ralf S. Engelschall <rse@engelschall.com> 
##

w3m="@l_prefix@/bin/w3m"
awk="@l_prefix@/bin/gawk"
html="@l_prefix@/share/jargon"

IDX='
    BEGIN {
        RS="<dt>"
    }
    /dt>$/ {
        while ((i = index($0, "&amp;")) > 0) {
            $0 = substr($0, 1, i-1) "&" substr($0, i+5);
        }
        split($0, a, "[<>\"]");
        if ((WORD != "" && tolower(a[5]) == tolower(WORD)) || (MATCH != "" && index(tolower(a[5]), tolower(MATCH)) > 0)) {
            if (PRINT == 1) {
                print a[3];
            } else {
                print a[5];
            }
            if (STOP > 0) {
                exit 0;
            }
        }
    }'
SHOW='
    /^--*$/ {
        a=1;
        next;
    }
    /--*$/ {
        a=0;
        next;
    }
    a==1 {
        print
    }'

if [ ".$1" = ".-h" ]; then
    echo "jargon                  - browse the whole jargon file"
    echo "jargon baz              - displays entry for keyword 'baz'"
    echo "jargon -d bar           - displays all entries whose keywords contain 'bar'"
    echo "jargon -l foo           - lists all keywords containing 'foo'"
    exit 0
elif [ ".$1" = . ]; then
    exec $w3m $html/index.html
elif [ ".$1" = ".-l" -a ".$2" != . ]; then
    shift
    $awk "$IDX" MATCH="$1" PRINT=2 STOP=0 $html/?.html
elif [ ".$1" = ".-d" -a ".$2" != . ]; then
    shift
    f=`$awk "$IDX" MATCH="$1" PRINT=1 STOP=0 $html/?.html`
    if [ ".$f" = . ]; then exit 0; fi
    for i in $f; do
        $w3m -dump "$html/$i" | $awk "$SHOW"
    done
else
    f=`$awk "$IDX" WORD="$1" PRINT=1 STOP=1 $html/?.html`
    if [ ".$f" = . ]; then exit 0; fi
    $w3m -dump "$html/$f" | $awk "$SHOW"
fi

