#!/bin/sh

#
# Version 2.2 - Tue Mar 22 15:09:08 CET 2022
# SPDsoft <spd@daphne.cps.unizar.es>
#
# query unizar directory
#
# Requires wget 
# Requires jshon http://kmkeen.com/jshon/
# Optional: recode/charconv
# Warning: 20131105 from Macports has a nasty bug. Compile your own version
# otherwise you'll get random fails with:
# json read error: line 32 column 1: unable to decode byte 0xff near 'u'
#

PATH=/usr/local/bin:$PATH
export PATH

check()
{
	if command -v $1 > /dev/null
	then
		:
	else
		echo "Please, install $1 first" >&2
		exit 1
	fi
}

check wget
check jshon

#
# I'll try to recode everything to plain old US-ASCII 7-bit charset
#
do_filter()
{
	if command -v recode > /dev/null
	then
		if command -v charconv > /dev/null
		then
			recode utf8..latin1 | charconv -fl -ta 
		else
			cat
		fi
	else
		cat
	fi
}

TMPFILE=${TMPDIR:-/tmp}/`basename $0`-$RANDOM-$$

on_exit()
{
    rm -f ${TMPFILE}
}

if [ -f ${TMPFILE} ]
then
	echo "Sorry, manually delete ${TMPFILE}" >&2
	exit 1
else
    touch ${TMPFILE} || exit 1
    trap "on_exit" INT 0 1 2 3 13 15
fi

umask 077

URL=https://directorio.unizar.es/rest/persona/persona_cadena
wget -q -O - \
	${URL}"?cadena=$1" |\
	do_filter > ${TMPFILE}

t=`jshon -l < ${TMPFILE}`
if [ $? -eq 1 ]
then
	t=1
fi

n=0
(
while [ $n -lt $t ]
do
	if jshon -e $n -k < ${TMPFILE} | grep extension >/dev/null 2>&1
	then
		jshon -e $n -e nombreApellidos \
			-u -p -e codigoCentro\
			-u -p -e codigoDepartamento \
			-u -p -e email \
			-u -p -e extension -u < ${TMPFILE} 2>/dev/null 
	else
		if jshon -e $n -k < ${TMPFILE} | grep email >/dev/null 2>&1
		then
			jshon -e $n -e nombreApellidos \
				-u -p -e codigoCentro\
				-u -p -e codigoDepartamento \
				-u -p -e email < ${TMPFILE} 2>/dev/null 
				echo "n.a."
		else
			:
		fi
	fi
	n=`expr $n + 1`
done 
) | ( while read name
do
	read codec
	read coded
	read mail
	read tel
	echo "$name|$tel|<$mail>"
done ) 

rm -f ${TMPFILE}

