#!/bin/sh

# disable filename globbing

 echo Content-type: text/html
 echo
APPLDIR=/ptovt
DATADIR=/usr/ptovt
PATH=$PATH:/ihd/bin:.
export PATH APPLDIR DATADIR
T=/tmp/T$$
T1=/tmp/T1$$
T2=/tmp/T2$$
splash >$T
awk -F= '$0=="" { next }
flag!="" && NF==2 { print "" ; flag="" }
NF==2 && index($0,"
") { printf "%s",$0;flag=1; next}
NF==1 && flag!="" { printf "%s",$0}
$2!="" && $1!="T00" ' $T > $T1
QRY=`awk -F= ' $1== "B1" {print $2} ' $T1 `
if [ "$QRY" = Consultar ]
then
	COMMAND=`awk -F= ' BEGIN { printf "/ihd/bin/ihmq desba " }
	$1!="B1" {
	if (NR==1 && substr($1,length($1)-1) !="00") printf "H00^ "
	if (substr($1,1,3)=="DOC") printf "D%s^%s ",substr($1,length($1)-1),adv($2)
	else printf "H%s^%s ",substr($1,length($1)-1),adv($2)
}
function adv(txt) { while (substr(txt,1,1)==" ") txt=substr(txt,2); return (txt) }
END {
print "" } ' $T1 `
$COMMAND | sort -t\^ -k2 -k1 -u  >$T2
NF=`awk ' END { print NR } ' $T2`
if [ $NF = 1 ]
then
		REG=`awk -F"^" ' { print $1 } ' $T2`
		desbaget.cgi $REG
	else
	desbalist.cgi $T $T2
	fi
fi
if [ "$QRY" = Actualizar ]
then
	COMMAND=`awk -F= ' END { printf "/ihd/bin/ihmu desba %s\n","'"$T2"'" } ' `
	awk -F= '
	/desbaH/ { printf "H%s%s\n",substr($1,length($1)-1),$2 }
	/desbaD/ { printf "D%s%s\n",substr($1,length($1)-3),$2 }
	' $T1 > $T2
echo -n " " >>$T2
	$COMMAND 
	cat ../desba.htm
fi
rm $T $T1 $T2
