#! /bin/sh
# replace <pro>ginette</pro> by a sequence like
# <a href="./ginette.html">ginette</a>
# we have to deal with the path of ginette.html ...
#
# see call in savesaxo.sh
#
# update :
# $Id$
#++ still not working perfectly because path of links on the different occurences of <pro>...</pro> may not be the same 
# ex: see restoreboxparam.pro : domdef and saveboxparam
# fplod 2007-06-26T13:32:06Z aedon.locean-ipsl.upmc.fr (Darwin)
# improvment for multiple occurences of <pro>...</pro> on one line
# see http://www.gentoo.org/doc/en/articles/l-sed2.xml 
# Sed by example, Part 2
# especially for directory-overview files
# fplod 2007-03-20T14:02:14Z aedon.locean-ipsl.upmc.fr (Darwin)
# creation
#
set -u
output=${1} # ++ parameter
#
# first find all files containing <pro>...</pro>
list_html_pro=$(find ${output} -name "*.html" -exec grep -l "<pro>.*</pro>" {} \;)
if [ "${list_html_pro}" = " " ]
then
   echo "iii : no <pro>...</pro> in html files"
else
   for file_html in ${list_html_pro}
   do
       fpath=$(dirname ${file_html} | sed -e "s+\(${output}/\)\(.*\)+\2+")
       list_llink=$(grep -n "<pro>.*</pro>" ${file_html} | awk -F ":" '{print $1}')
       for line in ${list_llink}
       do
          # replace <pro>something</pro> by
          #<a href="something.html">something</a>
          # module is the html file name to be used
          module=$(sed -ne "${line},${line}p" ${file_html} | \
                   grep "<pro>.*</pro>" | \
                   sed -e "s+\(.*<pro>\)\([^<]*\)\(</pro>.*\)+\\2.html+g")
          modulemin=$(echo ${module} | tr "[:upper:]" "[:lower:]" )
          # lpath is the path on module relatively to the location of
          # the html file containing the <pro>...</pro>
          lpath=$(find ${output} -name "${modulemin}")
          if [ "${lpath}" = "" ]
          then
             echo "eee : path of ${modulemin} not found under ${output}"
             echo "eee : ${module} is used in ${file_html}"
          else
             lpath=$(dirname ${lpath} | sed -e "s+\(${output}/\)\(.*\)+\2+")
#echo "path du fichier html ${fpath}"
#echo "lpath ${lpath}"
             if [ "${lpath}" = "${fpath}" ]
             then
                relpath="./"
             else
                nblev=$(echo ${fpath} |  sed -e "s@/\$@@" | awk -F "/" '{print NF}')
           #     nblev=$(( ${nblev} + 1))
                relpath=""
                ilev=1
                while [ ${ilev} -le ${nblev} ]
                do
                   relpath="${relpath}../"
                   ilev=$(( ${ilev} + 1 ))
                done
                relpath=${relpath}/${lpath}
             fi
#echo "relpath ${relpath}"
             sed -e "${line}s+\(<pro>\)\([^<]*\)\(</pro>\)+<a href=\"${relpath}/\\2.html\">\2</a>+g" \
             ${file_html} > ${file_html}_modify
             mv ${file_html}_modify ${file_html}
          fi
       done
   done
fi
exit 0
