#!/bin/bash

count_hierar()
{
	local count=0
	local src=${1}
	local str=
	while [ "${src}" != "" ]
	do
	str=${src%%/*}
	src=${src#*/*}
	if [ "$str" == "${src}" ]; then
		echo  ${count}
		return
	fi
	count=$((count+1))
	done
}

mk_spaces()
{
	local count=${1}
	local spaces=""
	for ((k=0;k<$count;k++))
	do
	spaces=${spaces}"    "
	done
	echo "${spaces}"
}

list_onedir()
{
	local relative=${1}
	local addflg=false
	local dir=
	cd "${relative}"
	[ "${relative}" == "." ] && relative=""
	if [ ${#relative} -gt 0 ]; then
		addflg=true
		WD="${WD}/${relative}"
	fi
	[ "${WD}" != "." ] && echo "${WD}">>${TMPFILE}

	find . -maxdepth 1 ! -name "." -type d|sort|while read i
	do
		dir=${i#*/}
		list_onedir "${dir}"
	done

	ls -tr ./*.{url,URL} 2>/dev/null|while read i
	do
		fname=${i#*/}
		echo "${WD}/${fname}">>${TMPFILE}
	done

	cd ..
	$addflg && WD=${WD%*/*}
}

analize_structure()
{
	local str=${befdirpath}
	local shallowcnt=0
	for ((j=$befhierarcnt;j>$hierarcnt;j--))
	do
		shallowcnt=$((shallowcnt+1))
		str=${str%*/*}
	done

	if [ "${str}" != "${dirpath}" ]; then
		shallowcnt=$((shallowcnt+1))
	fi
	echo ${shallowcnt}
	return
}

exitproc()
{ rm -f ${TMPFILE}; }
trap '
exitproc
exit 1
' 2 15

[ $# -lt 2 ] && echo "$0 favorites-dir bookmarks-file" && exit 1
BASEDIR=${1}
DESTFILE=${2}
hierarcnt=0
dirpath="."
spaces=""
[ "$(echo "${DESTFILE}"|cut -b 1)" != "/" ] && DESTFILE=$(pwd)/${DESTFILE}
cd "${BASEDIR}" 2>/dev/null
if [ $? -ne 0 ]; then echo "Can't move to ${BASEDIR}";exit 1;fi
BASEDIR=$(pwd)
TMPFILE=$(mktemp)

WD="."
list_onedir "."

cd "${BASEDIR}"

cat>"${DESTFILE}"<<EOT
<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
     It will be read and overwritten.
     DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>

<DL><p>
EOT

while read i
do
modifytime=$(stat -c %y "${i}"|sed 's/\-/\//g'|cut -b1-19)
adddate=$(date -d "${modifytime}" +%s)
befhierarcnt=${hierarcnt}
befdirpath=${dirpath}
fname=${i##*/}
[ -d "${i}" ] && i=${i}/
dirpath=${i%*/*}
hierarcnt=$(count_hierar "${dirpath}X")

if [ ${hierarcnt} -le ${befhierarcnt} -a "${dirpath}" != "${befdirpath}" ]; then
	shallowcnt=$(analize_structure)
	for ((j=$befhierarcnt;j>$(($befhierarcnt - $shallowcnt));j--))
	do
		spaces=$(mk_spaces $j)
		echo "${spaces}</DL><p>">>"${DESTFILE}"
	done
fi

spaces=$(mk_spaces $hierarcnt)

if [ -d "${i}" ]; then
	basename=${fname}
	cat>>"${DESTFILE}"<<EOT
${spaces}<DT><H3 ADD_DATE="${adddate}">${basename}</H3>
${spaces}<DL><p>
EOT
else
	basename=${fname%*\.url}
	basename=${basename%*\.URL}
	URL=$(grep "^URL"<"${i}"|cut -b 5-|sed 's/\n$//'|sed 's/\r$//')
	echo -n "    ${spaces}<DT><A ">>"${DESTFILE}"
	echo -n "HREF=\"${URL}\" ADD_DATE=">>"${DESTFILE}"
	echo "\"${adddate}\">${basename}</A>">>"${DESTFILE}"
fi
done<${TMPFILE}
echo "</DL><p>">>"${DESTFILE}"
exitproc
