#!/bin/sh
#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING! This script does not check its inputs and is
# therefore completely UNSAFE!
# Do not run it on any webserver reachable via a network!
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

# searches through search index files to get all 

# disable filename globbing
set -f

# The following paths were automatically inserted by wiki2statcz.pl
###### automatic path insert here #####

cd ${wikifilepath}/${lang}/search

getResFile()   # parameter $1=searchword
{
  searchword=$1
  # extract all possible matches
  len=${#searchword}
  wildcard=""
  lastchar=`echo $searchword | cut -b${len} `
  if [ $lastchar = "*" ]; then
    wildcard=".*"
    len=$(( $len - 1 ))
    searchword=`echo $searchword | cut -b-${len} `
  fi
  searchword=`echo $searchword | awk -- "{ a=tolower(\\$0); gsub(\"|||\",\"ae\", a ); gsub(\"|\",\"oe\", a); gsub(\"|\", \"ue\", a); gsub(\"\", \"ss\", a); gsub(\"[^a-zA-Z0-9]\", \"_\", a); gsub(\"[]\", \"a\", a); gsub(\"|\",\"c\",a); gsub(\"[]\",\"e\",a); gsub(\"[]\",\"i\",a); gsub(\"\", \"d\",a); gsub(\"|\",\"n\",a); gsub(\"[]\",\"o\",a); gsub(\"[]\",\"u\",a); gsub(\"[]\",\"y\",a);  print a }"`
  pathp1=`echo $searchword | cut -b-1 `
  if expr $len \< 2 >/dev/null; then
  pathp3=${pathp1}${pathp1}${pathp1}; 
  else
    if expr $len \< 3 >/dev/null; then
      pathp3=`echo $searchword | cut -b-2` 
    else
      pathp3=`echo $searchword | cut -b-3`
    fi
  fi
  indexname="${pathp3}.js"
  tar xzOf ${pathp1}.tgz $indexname | grep -i "\!${searchword}${wildcard}\!" | \
      sed -e '{ s/\!.*\!!//; s/::$// ; s/::/\n/g}' --  >> ${tempfile};
  # now we have all links for the search key in a line of its own
}


echo Content-Type: text/html\; charset=$wikicharset
echo

cat search1.ht



#echo argc is $#. argv is "$*".
arg=` echo $QUERY_STRING | cut -b8- | sed -e "{ s/\+/ /g ; s/\%2A/\*/g }" `
#arg=$*
# prepare for shifting
set -- $arg
tempfile="/tmp/wikizs-"`date +%s`
rm -f ${tempfile}
getResFile $1
sort ${tempfile} | uniq >${tempfile}-1
shift
# for all other words in the search term
while [ $# -ge 1 ] ;
do
  rm ${tempfile}
  getResFile $1
  # merging two files would be more efficient than sorting and 'uniq'ing one file, but 'merge' is not part of busybox
  sort ${tempfile} | uniq >${tempfile}-2
  sort ${tempfile}-1 ${tempfile}-2 | uniq -d >${tempfile}
  mv ${tempfile} ${tempfile}-1 
  shift # next word
done 
#Now we need to make links 
sed -e "{ s/\(.*\):\(.*\)/\<LI\>\<A href=\"\/cgi-bin\/wpg-${lang}?\2\.ht\"\>\1\<\/A\>/ }" < ${tempfile}-1
#rm -f ${tempfile} ${tempfile}-1 ${tempfile}-2 

echo "</BODY></HTML>"
#cat search2.ht


