#!/bin/sh

if [ 2 != $# ]
then	echo "** usage: trans-tree source-dir target-dir"
	exit 253
fi

# remember the present shell script file directory, to call siblings
SCRIPTNAME=trans-tree
CURDIR=`pwd`
SCRIPTDIR=`which $0 | sed -e "s%/$SCRIPTNAME%%" -e "/^[^/]/s%^%$CURDIR/%"`

SRC=$1 ; shift
DST=$1 ; shift

if [ ! -d $SRC ]
then 	echo "** source-dir $SRC doesn't exist"
	exit 253
fi

if [ ! -d $DST ]
then 	echo "** target-dir $DST doesn't exist"
	exit 253
fi

LM=/tmp/lm$$
LL=/tmp/ll$$

# pushdir
OLDWD=`pwd`
cd $SRC
# visit source tree, collect info:
# collect dir names
DIRS="" ; for i in `find . -type d -print` ; do DIRS="$DIRS $DST/$i" ; done
# collect .ll
find . \( -type f -o -type l \) -name "*.lm" -exec grep -s "^defmodule" {} \; -print > $LM
# collect .lm
find . \( -type f -o -type l \) -name "*.ll" -print > $LL
# popdir
cd $OLDWD

# create destination dirs
CREATEDDIRS=""
for DIR in $DIRS
do	if [ ! -d $DIR ]
	then	mkdir $DIR
		CREATEDDIRS="$DIR $CREATEDDIRS"
	fi
done

for RDP in `cat $LM`
do

ERR=0

DP=$SRC/$RDP

M=`basename $DP .lm`
if (grep -s "^files[ 	]*([|\"]\{0,1\}$M[|\"]\{0,1\})" $DP || grep -s "^files[ 	]*([|\"]\{0,1\}$M\.ll[|\"]\{0,1\})" $DP)
then sleep 0
else echo "** error: $DP should say \"files ($M)\" instead of:" >&2
     grep "^files" $DP >&2
     ERR=1
fi

LLOCC=`grep "/$M.ll" $LL | wc -l`
if [ 0 = $LLOCC ]
then	echo "** $M.ll not found in tree $SRC" >&2
	grep "/$M.ll" $LL >&2
	ERR=1
else	if [ 1 != $LLOCC ]
	then	echo "** multiple occurence of $M.ll in tree $SRC" >&2
		grep "/$M.ll" $LL >&2
		ERR=1
	fi
fi

LMOCC=`grep "/$M.lm" $LM | wc -l`
if [ 0 = $LMOCC ]
then	echo "** $M.lm not found in tree $SRC" >&2
	grep "/$M.lm" $LM >&2
	ERR=1
else	if [ 1 != $LMOCC ]
	then	echo "** multiple occurence of $M.lm in tree $SRC" >&2
		grep "/$M.lm" $LM >&2
		ERR=1
	fi
fi

DMP=$DST/`echo $RDP | sed -e "s%/$M[.]lm%%"`/$M

if [ -f $DMP.t ]
then	echo "** $DMP.t already exists"
	ERR=1
fi

if [ -f $DMP.td ]
then	echo "** $DMP.td already exists"
	ERR=1
fi

if [ $ERR = 0 ]
then	SP=`grep "/$M.ll" $LL`
	RP=`grep read-package $DP|sed -e "s/.*read-package \.//" -e "s/).*//"`
	$SCRIPTDIR/trans-source $M $SRC/$SP $RP > $DMP.t
	$SCRIPTDIR/trans-descr $M $DP $DMP.td $RP
	tail -1 $DMP.t
fi

done

# remove any empty target directory created
if [ "" != "$CREATEDDIRS" ]
then	rmdir $CREATEDDIRS 2>/dev/null
fi

rm $LL $LM

# summary of warnings
echo ";;; warnings because of" `grep "#|WARN" \`find $DST -type f -name "*.t" -print\` | sed -e "s/^.*#|WARN.*|# //" -e "s/ .*$//" -e "s/).*$//" | sort -u`
# echo warnings because of `grep "#|WARN" \`find $HOME/tmp/icos -type f -name "*.t" -print\` | sed -e "s/^.*#|WARN.*|# //" -e "s/ .*$//" -e "s/).*$//" | sort -u`

exit $ERR
