#!/bin/dash
## https://teamwork.gigaset.com/gigawiki/display/GPPPO/Online+directory?preview=/8421382/8585248/1.04.02.pub.2.public_pbs_protocol_spec.pdf

# typical invokation uri:
# /gigaset-prov/netdir?command=get_list&type=pb&fn=*&ln=*&ct=*&st=*&hm=01234567890&nr=*&mb=*&fx=*&sip=*&zc=*&em=*&in=*&bp=*&lang=3&first=1&count=1&mac=ACDE48234567&reqsrc=auto&handsetid=0000000000&limit=2048

# http://phonegw.lan.home.arpa/gigaset-prov/netdir?command=get_list&hm=01234567890
# or without cgi as: env REQUEST_URI='?hm=01234567890' ./netdir
# bulk review of carrier cdr:
# <  /tmp/x cut -d$'\t' -f2 | grep ^0 | tr -d " " | xargs -I{} env REQUEST_URI='?hm={}' ./netdir

# unfortunatly sl450go appears to cache results so changes may not be noticed on the phone ui
#env > /tmp/enquiry

IFS="?"
QUERY=$(echo "${REQUEST_URI}" | cut -d? -f2-)
#QUERY="$(printf "%.0s%s" ${REQUEST_URI})"
IFS="&"
eval $(for INEM in ${QUERY};do echo "netdir${INEM}" | grep ^[a-z]*=[0-9]*$; done)
IFS=

#OLDBASE=/var/local/mirror/https/static.ofcom.org.uk/static/numbering/
#OLDBASE=/var/local/mirror/https/www.ofcom.org.uk/__data/assets/file/*/*/
LONGURL=/var/local/mirror/https/www.ofcom.org.uk/siteassets/resources/documents/phones-telecoms-and-internet
BASE=${LONGURL}/information-for-industry/numbering/regular-updates/telephone-numbers/

#C0=$(echo ${netdirhm} | cut -c1)
C0=$(printf %.1s ${netdirhm})
if test "${C0}" = "0"
then
C1=$(echo ${netdirhm} | cut -c2)
C1P=$(echo ${netdirhm} | cut -c2-)
case "${C1}" in
 (1|2) FILE=s1.csv ;;
 (3) FILE=s3.csv ;;
 (5) FILE=s5.csv ;;
 (7) FILE=s7.csv ;;
 (8) FILE=s8.csv ;;
 (9) FILE=s9.csv ;;
esac
fi

LAST=""
FIRST=""
#CSV=$(eval echo "${BASE}${FILE}")
CSV=$(stat -c'%Y %n' ${BASE}${FILE}* | sort -g | tail -1 | cut -d" " -f2)
if test -f "${CSV}"
then
 until test "${#C1P}" -lt 4
 do
  REGEX="$(echo "${C1P}" | sed -s 's_._[^0-9,]*\0_g')"
  if RESULT="$(grep ^${REGEX} "${CSV}")"
  then
   XML="$(echo "${RESULT}" | sed -s '
s_&_&amp;_g;
s_<_&lt;_g;
s_>_&gt;_g;
s_^\([^,]*\),\([^,]*\),\([^,]*\),.*$_<entry><ln>'${netdirhm}'</ln><fn>\3</fn><hm>'${netdirhm}'</hm></entry>_g;
s_<ln></ln>_<ln>Unallocated</ln>_g;
')"
   break
  fi
  #C1P=$(echo "${C1P}" | rev | cut -c2- | rev)
  C1P="$(printf %.$(( ${#C1P} - 1))s "${C1P}")"
 done
fi

TOTAL=$(echo "${XML}" | grep '^<' | wc -l)

if test "${TOTAL}" -gt 0
then
echo "Status: 200 OK\r"
echo "Content-Type: text/xml; charset=utf-8\r"
echo "\r"
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"
echo "<list response=\"get_list\" type=\"pb\" total=\""${TOTAL}"\" first=\"1\" last=\""${TOTAL}"\">\r"
echo "${XML}\r"
echo "</list>\r"
else
echo "Status: 200 OK\r"
echo "Content-Type: text/xml; charset=utf-8\r"
echo "\r"
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r"
echo "<list response=\"get_list\" type=\"pb\" notfound=\"hm\" total=\"0\"/>"
fi
