#!/bin/bash

# convert netscape bookmark file to flat file
# subsequent script will load this flat file
# into database format used by bookmarker.
# I have separated the scripts to keep in line with
# the *nix ideal of "small tools". Use either
# script alone or together depending on what you
# need to do.

# parameter one to this script is the netscape bookmark file
BK_FILE=$1

# tmp file
TMP_FILE=/tmp/`basename $0`.$$

DEPTH=0
FOLDER1="unassigned"
FOLDER2="unassigned"
FOLDER3="unassigned"
FOLDER4="unassigned"

while read BK_LINE
do

  echo "$BK_LINE" | grep -qs "A HREF" 2>1 >/dev/null
  
  if [ $? -eq 0 ]
  then
    BOOKMARK=`echo "$BK_LINE" | sed 's%.*<A HREF="\(.*\)" ADD.*>\(.*\)</A>.*%\1\*\2%'`

    BK=`echo "$BOOKMARK" | sed -f ns_convert.sed`
    echo ${FOLDER1}*${FOLDER2}*${FOLDER3}*${FOLDER4}*${BK} >>$TMP_FILE
    continue
  fi


  echo "$BK_LINE" | grep -qs "<H3" 2>1 >/dev/null
  
  if [ $? -eq 0 ]
  then
    let "DEPTH = DEPTH + 1"
    FOLDER=`echo "$BK_LINE" | sed 's%.*<H3.*>\(.*\)</H3>.*%\1%'`

    if [ $DEPTH -eq 1 ]
    then
      FOLDER1=$FOLDER
    elif [ $DEPTH -eq 2 ]
    then
      FOLDER2=$FOLDER
    elif [ $DEPTH -eq 3 ]
    then
      FOLDER3=$FOLDER
    elif [ $DEPTH -eq 4 ]
    then
      FOLDER4=$FOLDER  
    else
      :
    fi
    continue    
  fi

  echo "$BK_LINE" | grep -qs "/DL" 2>1 >/dev/null
  
  if [ $? -eq 0 ]
  then
    if [ $DEPTH -eq 1 ]
    then
      FOLDER1="unassigned"
    elif [ $DEPTH -eq 2 ]
    then
      FOLDER2="unassigned"
    elif [ $DEPTH -eq 3 ]
    then
      FOLDER3="unassigned"
    elif [ $DEPTH -eq 4 ]
    then
      FOLDER4="unassigned"
    else
      :
    fi

    let "DEPTH = DEPTH - 1"
    continue
  fi
  
done <$BK_FILE

awk -f ns_convert.awk $TMP_FILE

#rm -f $TMP_FILE 2>/dev/null
