#!/bin/sh

# disable filename globbing

 echo Content-type: text/html
 echo
 BASE=`pwd`
{
APPLDIR=$BASE/appl
DATADIR=$BASE/data
PATH=$PATH:$BASE/ihd/bin:.
export PATH APPLDIR DATADIR
T=/tmp/T$$
T1=/tmp/T1$$
T2=/tmp/T2$$
splash >$T
awk -F= ' BEGIN { ret=sprintf("%c",13) }
$0=="" { next }
$1=="T00" { next }
substr($1,1,5)=="perso" && $2=="" { next }
/DOCperso/ { next }
{ wh="" }
substr($1,1,5)=="perso" && index($0,ret) >0 {
printf "%s",$0
        while (wh=="")
        {
                if (getline <= 0) wh=1
                if(substr($1,1,5)=="perso") 
                if (index($0,ret)==0)  { printf "\n%s\n",$0;wh=1 }
                else printf "%s",$0
                else  printf "%s",$0
        }
}
wh=="" && $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 perso " }
	$1!="B1" {
	if (NR==1 && substr($1,length($1)-1) !="00") printf "H00^ "
	if (substr($1,6,1)=="D") 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 {
if (NR==1) print "H00^ "
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`
		./persoget.cgi $REG
	else
	./persolist.cgi $T $T2
	fi
fi
if [ "$QRY" = Actualizar ]
then
	COMMAND=`awk -F= ' END { printf "./ihd/bin/ihmu perso %s\n","'"$T2"'" } ' `
	awk -F= '
	/persoH/ { printf "H%s%s\n",substr($1,length($1)-1),substr($0,10) }
	/persoD/ { printf "D%s%s\n",substr($1,length($1)-3),substr($0,12) }
	' $T1 > $T2
        awk -F= ' $1=="persoH00" { y=$2 }
                  $2=="NEWFOTO>>>" { x=$1 }
                  $1=="FOTO" {
                                split($2,ph,".")
                                shell=sprintf("rm -f ../IMAG/perso/%s%s.%s;mv -f \"../upload/uploads/%s\" ../IMAG/perso/%s%s.%s\n",x,y,ph[2],$2,x,y,ph[2])
                                system(shell)
                                printf "%s%s%s.%s\n",substr(x,6),x,y,ph[2] } ' $T1 >> $T2
echo -n " " >>$T2
	./pwb agend
	$COMMAND 
	cat ../perso
fi
 } 2> ./error/perso.err
rm $T $T1 $T2
