#!/bin/sh
#
PATH=/bin:/usr/bin:/sbin:/usr/sbin
umask 077
TEMP=/tmp/..%GiVpwd%$$

trap "rm -f $TEMP mymd5 genesrc;exit" 15 3 2 1
if [ $# -lt 1 ]
then
    echo Usage: $0 fichier-src
    exit
fi

CONF=./donnemdp.conf
CMD5=./mymd5
FSRC=$1
FSRCH=./donnemdp.h

if [ ! -f $CONF ]
then
    echo "Manque le fichier de configuration $CONF"
    exit
fi

nbstrn=`grep "^stracename" $CONF | awk '{print NF}'`
strn=`grep "^stracename" $CONF | awk '{print $2}'`
strnall=`grep "^stracename" $CONF | sed 's/stracename//'`
shn=`grep "^shellname" $CONF | sed 's/shellname//'`
nshn=`grep "^shellname" $CONF | awk '{print NF}'`
nshn=`expr $nshn - 1`
snshn=$nshn

while [ ! -x "$CMD5" ]
do
    echo "$CMD5 n'est pas un executable"
    printf "donner le chemin de la commande md5: "
    read CMD5
done

if [ "$strn" -a -f $strn ]
then
    echo $strnall | tr ' ' '\n' | while read nom
    do
      if [ -f $nom ]
      then
	  echo "T: $nom" >> $TEMP
	  echo "V: `$CMD5 $nom`" >> $TEMP
      fi
    done
fi

if [ "$shn" ]
then
    while [ $nshn -gt 0 ]
    do
      tt=`echo $shn | awk '{print $AA}' AA=$nshn`
      if [ ! -x $tt ]
      then
	  echo "$tt n'est pas un shell executable"
	  continue
      fi
      echo "S: $tt" >> $TEMP
      echo "U: `$CMD5 $tt`" >> $TEMP
      nshn=`expr $nshn - 1`
    done
fi

OK=no
CO=0
while [ "$OK" ]
do
    echo "Donner le chemin d'un programme devant appeler donnemdp [return pour finir]"
    printf  "==>: "
    read chemin
    if [ "$chemin" ]
    then
	if [ ! -r "$chemin" ]
	then
	    echo "$chemin n'est pas un fichier lisible"
        else
	    EMPR=`$CMD5 $chemin`
	    echo "C: $chemin"  >> $TEMP
	    echo "E: $EMPR" >> $TEMP
	    printf "Donnez le mot de passe associe: "
	    read MPWD
	    if [ "$MPWD" ]
	    then
		echo "P: $MPWD" >> $TEMP
	    else
		echo "Le mot de passe ne doit pas etre vide. Recommencez"
		OK=no
	    fi
	    CO=`expr $CO + 1`
	fi
	BOOL=ok
    else
	if [ "$BOOL" ]
	then
	    OK=""
	else
	    OK=no
	fi
    fi
done
ALEA=`date "+%S%H%M%a%W%j%B"`$$

if [ "$nbstrn" ]
then
    if [ $nbstrn -gt 1 ]
    then
	nbstrn=`expr $nbstrn - 1`
	echo >> $FSRCH
	echo "#ifdef TRACENAME" >> $FSRCH
	echo "#define NBDTN	$nbstrn" >> $FSRCH
	echo "struct trace traceaut[NBDTN];" >> $FSRCH
	echo "#endif"  >> $FSRCH
    fi
fi
if [ $CO -gt 0 -a -x genesrc -a -f donnemdp.src1 -a -f donnemdp.src2 ]
then
    cp donnemdp.src1 $FSRC
    ./genesrc $CO $ALEA $TEMP $snshn >> $FSRC
    if [ $? -gt 0 ]
    then
	rm -f $FSRC $TEMP mymd5 genesrc
	exit 1
    fi
    cat donnemdp.src2 >> $FSRC
else
    echo "Il manque des fichiers pour l'installation"
fi
rm -f $TEMP
exit 0
