#!/bin/sh

# disable filename globbing

APPLDIR=/ptovt
DATADIR=/usr/ptovt
PATH=$PATH:/ihd/bin:.
export APPLDIR PATH DATADIR
{
T1=$1
tosig=/tmp/tosig
ENTO=/tmp/ENTO
FEMI=`awk -F= ' /traspH01/ { print $2 } ' $T1`
NDOC=`awk -F= ' /traspH03/ { print $2+0 } ' $T1`
CLIE=`awk -F= ' /traspH07/ { print $2 } ' $T1`
FPAG=`awk -F= ' /traspH08/ { print $2+0 } ' $T1`
MONE=`awk -F= ' /traspH09/ { print $2 } ' $T1`
TIPO=`awk -F= 'BEGIN { tp["FV"]=33;tp["GD"]=52;tp["ND"]=56;tp["NC"]=61}
/traspH02/ { print tp[$2]} ' $T1`
[ "$TIPO" = 33 ] && MONE=""
a1=./DTE/$TIPO/D$NDOC.xml
[ "$FPAG" = 0 ] && FVEN=`date -d 'now + 0 days' +%Y-%m-%d`
[ "$FPAG" = 30 ] && FVEN=`date -d 'now + 30 days' +%Y-%m-%d`
[ "$FPAG" = 60 ] && FVEN=`date -d 'now + 60 days' +%Y-%m-%d`
[ "$FPAG" = 90 ] && FVEN=`date -d 'now + 90 days' +%Y-%m-%d`
[ "$FPAG" = 120 ] && FVEN=`date -d 'now + 120 days' +%Y-%m-%d`
[ "$FPAG" = 180 ] && FVEN=`date -d 'now + 180 days' +%Y-%m-%d`
Enc=ENC/$TIPO/Enc$NDOC
ENVIO=ENVIO/$TIPO/ENV-$NDOC"T"$TIPO".xml"
FCLIE=/tmp/CLIE
/ptovt/sh/clien $CLIE >$FCLIE
ff=`date +%Y-%m-%d`
{
awk -F= ' BEGIN {
tipodte[33]="FACTURA ELECTRONICA"
tipodte[52]="GUIA DE DESPACHO ELECTRONICA"
tipodte[56]="NOTA DE DEBITO ELECTRONICA"
tipodte[61]="NOTA DE CREDITO ELECTRONICA"
printf "TipoDTE^%s\n","'"$TIPO"'"
printf "TIPODTE^%s\n",tipodte["'"$TIPO"'"]
printf "Folio^%s\n","'"$NDOC"'"
printf "Timbre^%s/%s\n","'"$TIPO"'","'"$NDOC"'"
x="'"$FPAG"'"+0
if (x >0) x=2
else x=1
if ("'"$TIPO"'"==33)
{
	printf "FmaPago^%s\n",x
	printf "FchVenc^%s\n","'"$FVEN"'"
}
printf "RUTEmisor^77920090-6\n"
printf "RznSoc^COMPUTACION BUIN LIMITADA\n"
printf "GiroEmis^COMERCIO DE SUMINISTROS DE OFICINAS Y ARTICULOS DE ESCRITORIO EN GENERAL\n"
printf "Telefono^56 2 2822 1481\n"
printf "Acteco^523924\n"
printf "DirOrigen^SAN MARTIN 174\n"
printf "CmnaOrigen^BUIN\n"
printf "CiudadOrigen^SANTIAGO\n"

	getline < "'"$FCLIE"'"
	split($0,cli,"^")
	cli[3]=substr(cli[3],1,40)
	split("'"$FEMI"'",dd,"/")
	printf "FechaFactura^%s\n","'"$FEMI"'"
	fecu=dd[3]dd[2]dd[1]
	printf "FchEmis^%.4d-%.2d-%.2d\n",dd[3],dd[2],dd[1]
	printf "RUTCliente^%s\n",trail(cli[1])
	printf "RUTRecep^%s\n",trail(sacap(cli[1]))
	printf "RznSocRecep^%s\n",trail(cli[3])
	printf "GiroRecep^%s\n",trail(cli[4])
	printf "DirRecep^%s\n",trail(cli[5])
	printf "CmnaRecep^%s\n",trail(cli[6])
	printf "CiudadRecep^%s\n",trail(cli[7])
ref=0
}
function trail(txt) { while (substr(txt,length(txt),1)==" ") txt=substr(txt,1,length(txt)-1)
return (txt) }
function sacap(txt) { for (i=1;i<=length(txt);i++) if (substr(txt,i,1)!=".") tx=tx""substr(txt,i,1)
return (tx) }
FILENAME==ARGV[1] { cur[$1]=$2;next }
FILENAME==ARGV[3] { if(substr($1,1,6)==rg) 
		{
			split($0,rft,"^")
			split(rft[5],ddr,"/")
			printf "FchRef%.2d^%.4d-%.2d-%.2d\n",++ref,ddr[3],ddr[2],ddr[1]
			printf "TpoDocRef%.2d^%s\n",ref,52
			printf "NroLinRef%.2d^%s\n",ref,ref
			printf "FolioRef%.2d^%s\n",ref,rft[3]
			printf "RazonRef%.2d^%s\n",ref,"OC: "rft[6]
		}
}
/traspH00/ { rg=$2 ; next }
/traspH09/ { dg=$2 ; next }
/traspH08/ { fp=$2 ; next }
/traspH10/ { oc=$2 ; next }
/traspH11/ { it=$2 ; next }
/traspD..00/ { ll[++r]=substr($1,7,2)}
/traspD/ { rx[substr($1,7)]=$2;next}
END {
#printf "\n%29s%-16s%-30s%s\n\n\n\n\n\n\n","",cli[9],oc,fp
	printf "OrdendeCompra^%s\n",oc
	printf "TelefonoCliente^%s\n",cli[9]
	printf "CondicionesVenta^%s\n",fp
	if ("'"$TIPO"'"==33) RF01="RazonRef00^"
	if ("'"$TIPO"'"==52) 
	{
		printf "TipoDespacho^%s\n",substr(it,1,1)
		printf "IndTraslado^%s\n",substr(it,3,1)
		if(substr(it,3,1)==1)
		RF01="RazonRef00^TIPO DE TRASLADO 1;OPERACION CONSTITUYE VENTA"
		if(substr(it,3,1)==5)
		RF01="RazonRef00^TIPO DE TRASLADO 5;TRASLADOS INTERNOS"
	}

lin=0
for (j=0;j<r;j++)
{
	rr=sprintf("%.2d",j)
	if(substr(rx[rr"00"],1,1)==".")
	{
			#printf "COM %12s %s\n",rrx,rx[rr"02"]
		if("'"$TIPO"'" == 61) rf=33
		if("'"$TIPO"'" == 56) rf=61
		if("'"$TIPO"'" == 33) rf=52
		if(substr(rx[rr"02"],1,1)!="" && substr(rx[rr"02"],1,1)!=" ")
		{
			if(substr(rx[rr"02"],1,5)=="CASO ") rf="SET"
			split(rx[rr"01"],rrz,"-")
			#printf "ATENC %12s %s",rrx,rx[rr"02"]
			#printf "%12s %s",rrx,rx[rr"02"]
			#printf "%12s %s",rrx,rx[rr"02"]
			if (rrz[2]!="")
			{
				printf "FchRef%.2d^%.4d-%.2d-%.2d\n",++ref,dd[3],dd[2],dd[1]
				printf "TpoDocRef%.2d^%s\n",ref,rf
				printf "NroLinRef%.2d^%s\n",ref,ref
				if(rf=="SET") printf "FolioRef%.2d^%s\n",ref,rrz[2]
				else
				{
					printf "FolioRef%.2d^%s\n",ref,rrz[1]
					printf "CodRef%.2d^%s\n",ref,rrz[2]
				}
				printf "RazonRef%.2d^%s\n",ref,rx[rr"02"]
			}
		}
		else if("'"$TIPO"'"==52&&substr(rx[rr"02"],1,1)!=""&&substr(rx[rr"02"],1,1)!=" ") RF01=RF01";"rx[rr"02"]
		else if("'"$TIPO"'"==33&&substr(rx[rr"02"],1,1)!=""&&substr(rx[rr"02"],1,1)!=" "&&substr(rx[rr"02"],6,1)!="/") RF01=RF01""rx[rr"02"]";"
	}
	else
	{
		if("'"$MONE"'"=="USD" && "'"$TIPO"'"==52 ) tas=cur[fecu]
		else tas=1
		rrx=rx[rr"01"]
		if(rrx!="" && rrx!="EXENTO") printf "VlrCodigo%.2d^%s\n",++lin,rx[rr"01"]
		else printf "VlrCodigo%.2d^%s\n",++lin,rx[rr"00"]
		printf "NroLinDet%.2d^%d\n",lin,lin
		printf "DescripcionItem%.2d^%s\n",lin,rx[rr"02"]
		printf "NmbItem%.2d^%s\n",lin,rx[rr"02"]
		if(rx[rr"03"]+0)
		{
			printf "UnmdItem%.2d^%s\n",lin,"UN"
			printf "QtyItem%.2d^%.1f\n",lin,rx[rr"03"]
			if(rx[rr"04"]+0) printf "PrcItem%.2d^%.4f\n",lin,rx[rr"04"]*tas
			if (tas!=1)
			{
				printf "Moneda%.2d^%s\n",lin,dg
				printf "PrcOtrMon%.2d^%.4f\n",lin,rx[rr"04"]
				printf "FctConv%.2d^%.4f\n",lin,tas
			}
		}
		if (substr(rrx,1,6)=="EXENTO")
		{
			toti=sprintf("%.0f",rx[rr"04"]*rx[rr"03"]*tas)
			toto=sprintf("%.2f",rx[rr"04"]*rx[rr"03"])
			tte +=toti
			tteo +=toto
			printf "IndExe%.2d^%d\n",lin,1
		}
		else if (substr(rrx,1,3)=="DSC")
		{
			subti=sprintf("%.0f",rx[rr"04"]*rx[rr"03"]*tas)
			subto=sprintf("%.2f",rx[rr"04"]*rx[rr"03"])
			desc=sprintf("%.0f",subti*substr(rrx,4)*tas/100+.005)
			desco=sprintf("%.2f",subti*substr(rrx,4)/100+.005)
			toti=subti-desc
			toto=subto-desco
			printf "DescuentoPct%.2d^%.2f\n",lin,substr(rrx,4)
			printf "DescuentoMonto%.2d^%.0f\n",lin,desc
			if (tas!=1) printf "DctoOtrMnda%.2d^%.4f\n",lin,desco
		}
		else
		{
			toti=sprintf("%.0f",rx[rr"04"]*rx[rr"03"]*tas)
			toto=sprintf("%.2f",rx[rr"04"]*rx[rr"03"])
		}
		printf "MontoItem%.2d^%.0f\n",lin,toti
		if(tas!=1) printf "MontoItemOtrMnda%.2d^%.4f\n",lin,toto
		tt += toti
		tto +=toto
	}
}
print RF01
printf "LineasdeDetalle^%d\n",lin
printf "LineasdeReferen^%d\n",ref
cnt=0
cod=0
for (i in can)
{
	cod++
	cnt +=can[i]
}
	if(substr(dg,1,3)=="DSC") dg=substr(dg,4)
	st=sprintf("%.0f",tt-tte)
	if (dg+0 > 55)
	{
		printf "TpoValor^$\n",st
		dgg=sprintf ("%.0f",dg/1.19)
		printf "ValorDR^%.0f\n",dg/1.19
	}
	else if(dg >0)
	{
		dgg=sprintf("%.0f",st*dg/100+.005)
		printf "TpoValor^%%\n",st
		printf "ValorDR^%s%%\n",dg+0
	}
	nt=sprintf("%.0f",st-dgg)
	tt=sprintf("%.0f",nt*1.19+.005)
	iv=tt-nt
	tt +=tte
	printf "SubTF^%s\n",st
	printf "DescF^%s\n",dgg
	printf "MntNeto^%s\n",nt
	printf "MntExe^%s\n",tte
	printf "TasaIVA^19\n"
	printf "IVA^%s\n",iv
	printf "MntTotal^%s\n",tt
	#printf "FchEmis^%s\n","'"$ff"'"
	if (tas!=1)
	{
		printf "OtraMoneda^1\n"
		printf "TpoMoneda^DOLAR USA\n"
		printf "TpoCambio^%s\n",tas
		printf "MntNetoOtrMnda^%s\n",tto
		printf "MntExeOtrMnda^%s\n",ttoe
		printf "IVAOtrMnda^%.4f\n",tto*.19
		printf "MntTotOtrMnda^%.4f\n",tto*.19+tto
	}
} ' USD $T1 FFGG1 | ./chrs> $Enc

awk -F^ ' BEGIN {
print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"

printf "<DTE version=\"1.0\">\n"

printf "	<Documento ID=\"F%.6dT%s\">\n","'"$NDOC"'","'"$TIPO"'"
}
$1=="LineasdeDetalle" { det=$2+1 ; next }
$1=="LineasdeReferen" { ref=$2+1 ; next }
FILENAME == ARGV[1] { ste[$1]=trail($2);next }
NF==2 { if(ste[$1]!="") printf $2"\n",ste[$1] ; next }
{ print }
function trail(txt) { while (substr(txt,length(txt),1)==" ") txt=substr(txt,1,length(txt)-1)
return (txt) }
END {
	file="./DTE/Detalle"
	fileo="./DTE/OtrMnda"
	for (i=1;i<det;i++)
	{
		while ((getline < file) >0)
		{
			if (NF==2)
			{
				rr=sprintf("%s%.2d",$1,i)
				if(ste[rr]!="") printf $2"\n",ste[rr]
			}
			else print
			if ($1=="PrcItem")
			if ("'"$MONE"'"=="USD")
			{
				while ((getline < fileo) >0)
				{
					if (NF==2)
					{
						rr=sprintf("%s%.2d",$1,i)
						if(ste[rr]!="") printf $2"\n",ste[rr]
					}
					else print
				}
			}
		}
		close(file)
		close(fileo)
	}

	file="./DTE/DscRcgGlobal"
	if(ste["ValorDR"]!="") 
	{
		while ((getline < file) >0)
		{
			if (NF==2)
			{
				#rr=sprintf("%s%.2d",$1,i)
				if(ste[$1]!="")printf $2"\n",ste[$1]
			}
			else print
		}
		close(file)
	}
	file="./DTE/Referencia"
	for (i=1;i<ref;i++)
	{
		while ((getline < file) >0)
		{
			if (NF==2)
			{
				rr=sprintf("%s%.2d",$1,i)
				if(ste[rr]!="")printf $2"\n",ste[rr]
			}
			else print
		}
		close(file)
	}
	file="./DTE/TED"
	getline < file
	print
	while ((getline < file) >0)
	{
		if(NF==2) printf $2"\n",ste[$1]
		else  print 
		if(NF==2)  message=message""sprintf($2,ste[$1])
		else  message=message""sprintf("%s",$0)
	}
	close(file)
	file="./DTE/CAF."'"$TIPO"'"/CAF"
	while ((getline < file) >0) { message=message""sprintf("%s",$0);print}
	comm="date +%Y-%m-%dT%T"
	comm | getline
	printf "<TSTED>%s</TSTED>\n</DD>\n",$0
	message=message""sprintf("<TSTED>%s</TSTED></DD>",$0)
	printf "%s",message > file".mess"

}
 ' $Enc ./DTE/Encabezado
	
FRMT=/tmp/FRMT
sh firma DTE/CAF.$TIPO/CAF.mess $TIPO >$FRMT
awk ' { FRMT=FRMT""$0 }
END {
	printf "<FRMT algoritmo=\"SHA1withRSA\">%s</FRMT>\n",FRMT
	comm="date +%Y-%m-%dT%T"
	comm | getline
	printf "</TED>\n<TmstFirma>%s</TmstFirma>\n</Documento>\n",$0
} ' $FRMT
awk -F"^" ' NF==2 { printf $2"\n",sprintf(" URI=\"#F%.6dT%s\"","'"$NDOC"'","'"$TIPO"'");next}
{print }
END {
print "</DTE>"
} ' ./DTE/Signature 
}  > $tosig.1
xmllint --format $tosig.1 >$tosig
xmlsec1 --sign --privkey-pem KEYS/RAN.key,KEYS/RAN.crt --id-attr:ID Documento $tosig > $a1
xmlsec1 --verify --trusted-pem KEYS/RAN.pem --id-attr:ID Documento $a1
{
awk -F"^" ' BEGIN { "date +%Y-%m-%dT%T" | getline ste["TmstFirmaEnv"]
ste["SetDTE"]=sprintf("SET%.6dT%s","'"$NDOC"'","'"$TIPO"'")
}
FILENAME == ARGV[1] { ste[$1]=$2 }
FILENAME == ARGV[2] {
if (NF==2) printf $2"\n",ste[$1]
else print
}
FILENAME == ARGV[3] && FNR > 1  { print  }
END {

print "</SetDTE>"
print "</EnvioDTE>"
} ' $Enc /var/www/cgi-bin/DTE/EnvioDTE $a1
} >$ENTO
./sign3.py $ENTO KEYS/RAN.key KEYS/RAN.crt | awk ' NR==1 || NR > 5 ' >$ENVIO
awk '
function lead(txt) { while (substr(txt,1,1)==" ") txt=substr(txt,2); return txt }
/<TED/ { x=1 }
x==1 { x1=x1""lead($0) }
/<\/TED>/ { x=0 }
END {
printf "<?php\n"
printf "require_once(dirname(__FILE__).%c/../tcpdf_barcodes_2d_include.php%c);\n",39,39
printf "$barcodeobj = new TCPDF2DBarcode(%c%s%c, %cPDF417%c);\n",39,x1,39,39,39
printf "$barcodeobj->getBarcodePNG(1, 1, array(0,0,0));\n"
}
' $ENTO  > ../html/tcpdf/$TIPO/$NDOC.php
#cat  $a1
./prdtec $Enc
#rm -f $tosig $ENTO $FCLIE $FRMT DTE/CAF."'"$TIPO"'"/CAF.mess* 

} 2>tmp/Err
#awk ' { print $0"<br>" } ' tmp/Err
#awk ' { print $0"<br>" } ' $Enc
