#!/bin/sh
appname=`basename "$0"`
ver="0.4b.2003050217"
copy="2002, 2003"
mail="PointedEars@gmx.de"
mail_feedback="bug-htDICT@PointedEars.de"
# ----------------------------------------------------------------------------
#     htDICT 0.4b -- DICT-Via-HTTP Command-Line Client
#     Copyright (C) 2002, 2003  Thomas Lahn <PointedEars@gmx.de>
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with this program; if not, write to the Free Software
#     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
## Standard shell script disclaimer blurb thing:
##
## This script is a hack.  It's brute force.  It's horrible.
## It doesn't use Artificial Intelligence.  It doesn't use Virtual Reality.
## It's not perl.  It's not python.  It probably won't work unchanged on
## the "other" thousands of unices.  But it worksforme.  --ramiro
# (from /usr/local/mozilla/run-mozilla.sh)
#
#     This is work in progress. If you have an improvement, patch,
#     idea, whatever, on how to make this script better, please
#     send it to <bug-htdict@PointedEars.de>

function Title {
  echo "
${extd}htDICT $ver -- DICT-Via-HTTP Command-Line Client${norm}
Copyright (C) $copy  Thomas Lahn <$mail>
Distributed under the terms of the GNU General Public License (GPL),
see COPYING file or http://www.fsf.org/copyleft/gpl.html for details.
See http://dict.org/ for further information about the DICT protocol.
" | $fold
}

function help {
  echo "${extd}${appname}${norm}
  [${extd}-hVi${norm}] [${extd}-u${norm} UA] \
[ ( ${extd}-d${norm} DB_ID | ${extd}-D${norm} | ${extd}-l${norm} ) ] \
( ${extd}--info${norm} | [${extd}-t${norm} S_TYPE] QUERY )

  ${extd}-h${norm}, ${extd}--help${norm}          Display this help and exit.
  ${extd}-V${norm}, ${extd}--version${norm}       Display version information \
and exit.
  ${extd}-i${norm}, ${extd}--interactive${norm}   Interactive mode (browsing)
  ${extd}-u${norm}, ${extd}--user-agent${norm}    Use the HTTP user agent \
specified by UA.
    UA                  Default is \`links' (preferred) or \`lynx'.
                        For proper non-interactive mode, the user agent must
                        support the \`-dump' argument to dump the rendered
                        search result to the standard output.
  ${extd}-d${norm}, ${extd}--database${norm}      Search only the database(s) \
specified by DB_ID.
    DB_ID               ${extd}*${norm}           any (default)
                                      Note that \`${extd}*${norm}' is a special shell
                                      character for \"all files in current
                                      directory\" and must be escaped (${extd}\\*${norm}),
                                      quoted (${extd}'*'${norm}) or double-quoted (${extd}\"*\"${norm}).
                        ${extd}!${norm}           First match
  ${extd}-D${norm}, ${extd}--Databases${norm}     List available databases with their DB_ID.
  ${extd}-l${norm}  ${extd}--list${norm}          Same as \`${extd}-D${norm}'.
  ${extd}-I${norm}, ${extd}--info${norm}          Show database copyright information instead\
 of
                        performing a query.
  ${extd}-t${norm}, ${extd}--type${norm}          Use search strategy specified\
 by S_TYPE.
    S_TYPE              ${extd}*${norm}           Return definitions (default)
                                      Note that \`${extd}*${norm}' is a special shell
                                      character for \"all files in current
                                      directory\" and must be escaped (${extd}\\*${norm}),
                                      quoted (${extd}'*'${norm}) or double-quoted (${extd}\"*\"${norm}).
                        ${extd}exact${norm}       Match words exactly
                        ${extd}prefix${norm}      Match prefixes
                        ${extd}substring${norm}   Match substring occurring anywhere in word
                        ${extd}suffix${norm}      Match suffixes
                        ${extd}re${norm}          POSIX 1003.2 (modern) regular expressions
                        ${extd}regexp${norm}      Old (basic) regular expressions
                        ${extd}soundex${norm}     Match using SOUNDEX algorithm
                        ${extd}lev${norm}         Match words within Levenshtein distance one
  QUERY               Database query string.
  
All DICT options may be subject to change."
  if [ $getopt_type = "short" ]; then
_XPG=1
    echo "
Note that the long options are not available on this
system, so you must use the short options instead." | $fmt
_XPG=0
  fi
  echo
}

# from /etc/rc.status

if test -z "$LINES" -o -z "$COLUMNS" ; then
    eval `stty size 2>/dev/null | (read L C; \
    echo LINES=${L:-24} COLUMNS=${C:-80})`
fi
test $LINES   -eq 0 && LINES=24
test $COLUMNS -eq 0 && COLUMNS=80

if test "$TERM" != "raw" && stty size >/dev/null 2>&1 ; then
  esc=`echo -en "\033"`
  extd="${esc}[1m"
  norm=`echo -en "${esc}[m\017"`
else
  esc=""
  extd=""
  norm=""
fi

# check for fold
fold="fold -sw $COLUMNS"
chk=`which fold 2> /dev/null`
test -z "$chk" && fold="cat"
chk=`echo x | $fold 1> /dev/null`
test -n "$chk" && fold="cat"

# check for fmt
fmt=cat
if [ $COLUMNS -ne 80 ]; then # output is preformatted for 80 cols
  chk=`which fmt 2>/dev/null`
  if [ $? -ne 0 ]; then
    fmt=$fold
  else
    # check for columns
    fmt="fmt -$COLUMNS"
    chk=`echo x | $fmt 2>/dev/null`
    test -z "$chk" && fmt="fmt"
    # check for -c|--crown-margin
    chk=`echo x | $fmt -c 2>/dev/null`
    if [ -n "$chk" ]; then
      fmt=$fmt" -c"
    else
      chk=`echo x | $fmt --crown-margin 2>/dev/null`
      test -n "$chk" && fmt=$fmt" --crown-margin"
    fi
  fi
fi

Title

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need `tmp' as the `eval set --' would nuke the return value of getopt.

#   echo "${extd}`basename $0`${norm}
#   [${extd}-i${norm}] [${extd}-u${norm} UA] [${extd}-t${norm} S_TYPE] \
# [ ( ${extd}-d${norm} DB_ID | ${extd}-D${norm} | ${extd}-l${norm} ) ] \
# [ ( ${extd}--info${norm} | QUERY ) ]

if `getopt -T >/dev/null 2>&1` ; [ $? = 4 ] ; then
  getopt_type=long
  tmp=`getopt -o hViu:t:d:DlI \
              -l help,version,interactive,user-agent:,type:,database:,\
Databases,list,info \
              -n "$appname" -s sh \
              -- "$@"`
else
  getopt_type=short
  tmp=`getopt hViu:t:d:DlI "$@"`
fi

getopt_exit_code=$?
help=0
version=0
ua=""
opt=-dump
db=*
if [ $getopt_exit_code -eq 0 ]; then
##     getopt  returns  error  code 0 for successful parsing, 1 if
##     getopt(3) returns errors, 2 if it does not understand  its
##     own parameters, 3 if an internal error occurs like out-of-
##     memory, and 4 if it is called with -T.
#
# Note the quotes around `$tmp': they are essential!
  eval set -- "$tmp"
  while true ; do
    case "$1" in
      -h | --help)                    help=1; shift;;
      -V | --version)                 version=1; shift;;
      -i | --interactive)             opt=""; shift;;
      -u | --user-agent)              ua=$2; shift 2;;
      -d | --database)                db=$2; shift 2;;
      -l | --list | -D | --Databases) query="-D"; shift;;
      -I | --info)                    query="--info"; shift;;
      -t | --type)                    type=$2; shift 2;;
      --) shift; break;;
      *) echo "Internal error!" ; exit 1;;
    esac
  done
  test -z "$query" && query="$*"
else
#   echo "getopt exited: $getopt_exit_code
#   " >&2
  test $getopt_exit_code -eq 1 -o $getopt_exit_code -eq 2 && echo && help=1
fi

if [ $getopt_exit_code -eq 0 ] && [ $version -eq 0 ] && [ -z "$query" ]; then
  echo "You need to provide at least a query string."
  echo
  help=1
fi

test $help -eq 1 && help

echo "Send suggestions and bug reports to <$mail_feedback>
" | $fold

test $version -eq 1 && exit 0
test $help -eq 1 && exit 255

if [ -z "$ua" ]; then
  # check for links
  chk=`which links 2> /dev/null`
  if [ $? -eq 0 ]; then
    ua=links
  else
    chk=`which lynx 2> /dev/null`
    if [ $? -eq 0 ]; then
      ua=lynx
    else
      echo "`basename $0`: No appropriate user agent detected.
      "
      exit 255
    fi
  fi
fi

if [ "$query" = "--info" ]; then
  query=00-database-info
else
  query=`echo $query | sed 's/ /+/g'`
fi
$ua $opt "http://www.dict.org/bin/Dict?Form=Dict2&Database=$db&Strategy=$type&Query=$query"

echo
