#!/bin/bash

# File:     index
# Created:  2004-03-26
# Modified: 2004-04-01
# Author:   Safranek David
# E-Mail:   safrad@email.cz

# clear

#global Depth=0

#Recursive Function
SubDir() {
#	global Depth=$(expr $Depth + 1)
	echo "Reading: $1" #, Depth: $Depth"
#	rm "$1"index.html
#	ls -1 $1 >tmp
	
	local s='<HEAD> <TITLE>'$1'</TITLE> </HEAD> <BODY> <P><A HREF="../index.html">..</A></P>'
	
	#cat tmp | echo
	#while [ tmp ]; do
#	cd $1
	for file in "$1"* #`ls -1 $1` #"$1"*
	do
	# return * for empty directory
		d1="$file" # ffds/kk => kk
		d1=`basename "$file"`
		d2="$1"$d1
		# if test -d "$d2" then
		if [ "$d1" = "." ]; then
		    echo "."
		elif [ "$d1" = ".." ]; then
		    echo ".."
		elif [ -d "$d2" ]; then
		    # Directory
		    s=$s'<P><A HREF="'$d1'/index.html">'$d1'/</A></P>'
#		    cd "$d1"
		    SubDir "$d2/"
#		    cd ".."
		elif [ -f "$d2" ]; then
		    # File
		    s=$s'<P><A HREF="'$d1'">'$d1'</A></P>'
		    echo "Adding file: $d2"
		else
		    echo "Skip: $d2"
		fi
		
	done
#	cd ..	
	s=$s'</BODY>'
	echo "Saving $1index.html"
	echo $s | cat >"$1index.html"
#	rm tmp
#	Depth=$(expr $Depth - 1)
}

#Parameters
if [ $# -gt 1 ]; then
    echo 'Too many parameters'
    exit
#elif [ "$#" -e 0 ]; then
#    echo 'Directory argument required'
else
    Dir=$1
fi

echo 'Creating Index.html Files'

#echo 'Start dir is:' $Dir

SubDir $Dir

echo 'Done'