#!/bin/bash
#
# mkhtm : Fabrique une table html pour un moteur
#
#
# D'abord quelques petites fonctions:
#
# Fonction trimurl 
# ################
# 
# Pour raccourcir les Urls afin de ne pas avoir des tables trop larges..
# 
# $1 : string. Si string > 12 coupe avec ...
# 
trimurl () {
    local mx=$2
    if [ ${#1} -ge $mx ]; then
    echo "${1:0:${mx}}..."
    else
    echo $1
    fi
}
# 
# Fonction table3col
# ##################
#
# crée 3 cellules de ligne d'une table à 3 colonnes =
< urls , path fichier local , path fichier nettoyé >
# avec les références qui vont bien. 
#
# $1 : path d'un fichier d' urls : 
# $2 : expression recherchée 
# $3 : moteur
#
# Ex : table3col
/mnt/memory_card/inalco/ProgrammationEtProjetEncadre/projet/AleksEtYAnn/pages/google/barrage-hydraulique/urls
barrage-hydraulique google
table3col () {
urls=$1
motcle=$2
moteur=$3
templatecell='__1<br/>'
templatehref='<a href="__1">__2</a>'
echo '<td>'
for url in `cat $urls`; do
    url1=$url
    txtu1=$(trimurl $url 70)
    fld1=$(echo $templatehref | sed -e "s!__1!$url1!g"
-e "s!__2!$txtu1!g" )
    echo $templatecell | sed -e "s!__1!$fld1!g" 
done
echo '</td><td>'
for url in `cat $urls`; do
    url2="../pages/${moteur}/${motcle}/$(basename $url)"
    txtu2=$(trimurl $(basename $url) 15)
    fld2=$(echo $templatehref | sed -e "s!__1!$url2!g"
-e "s!__2!$txtu2!g" )
    echo $templatecell | sed -e "s!__1!$fld2!g"
done
echo '</td><td>'
for url in `cat $urls`; do
    url3="../result/${moteur}/${motcle}/$(basename $url)"
    txtu3=$(trimurl $(basename $url) 15)
    fld3=$(echo $templatehref | sed -e "s!__1!$url3!g"
-e "s!__2!$txtu3!g" )
    echo $templatecell | sed -e "s!__1!$fld3!g" 
done
echo '</td>'
}
#
# crée une table relative à un moteur.
# pour obtenir la liste des mots clés , on boucle sur le
répertoire associé au moteur
#
# $1 : full path du répertoire du moteur sous le
répertoire pages
# ex :
/mnt/memory_card/inalco/ProgrammationEtProjetEncadre/projet/AleksEtYAnn/pages/google
#
tablemoteur () {
    local droot=$1
    local moteur=$(basename $droot)
    local th='<tr><td
align="center">__1</td><td
align="center">__2</td><td
align="center">__3</td><td
align="center">__4</td></tr>'
    echo '<html><body>'
    echo '<table style="text-align: left; width:
100%;" border="1" cellpadding="2" cellspacing="2"><tbody>'
    echo '<tr>''<th style="text-align: center;"
colspan="4" rowspan="1">'$moteur'</th>''</tr>'
    echo $th | sed -e "s!__1!Mots recherchés!g"
-e "s!__2!Urls retenues!g" -e "s!__3!Fichier local!g" -e
"s!__4!Après traitement!g"
    for d in $(ls -1 $droot) ; do
    echo '<tr>'
    echo '<td align="center">'$d'</td>'
    echo $(table3col $1/$d/urls $d $moteur)
    echo '</tr>'
    done
    echo
'</tbody></table></body></html>'
}
# Ca commence ici
# 
tablemoteur $1 > $2
echo "Table $2 crée."
exit