#!/bin/sh
SED=`which sed`
if test "x$SED" = "x"; then
    echo "ERROR: sed not found"
    exit
fi
ICONV=`which iconv`
if test "x$ICONV" = "x"; then
    echo "ERROR: iconv not found"
    exit
fi

CONVTEST=`LANG=C iconv -f UTF-8 -t UTF-8 ~/.dillo/bm.txt -o ~/.dillo/bm.txt.update 2>&1| sed -e "s/.*illegal.*/illegal/g"`

rm -f ~/.dillo/bm.txt.update
if test "x$CONVTEST" = "xillegal"; then
    echo "bookmark needs update."
else
    echo "already updated.(or no bookmark)"
    exit
fi

CHARSET=`locale | grep "LC_CTYPE.*\." | sed -e "s/^.*\.//g" -e "s/\"//g"`
if test "x$CHARSET" = "x"; then
    CHARSET="iso88591"
fi

case $CHARSET in
	iso885915@euro)
        CHARSET="iso885915"
        ;;
	koi8t)
        CHARSET="koi8-t"
        ;;
	utf8*)
        CHARSET="utf8"
        ;;
esac

CONVTEST=`LANG=C iconv -f $CHARSET -t UTF-8 ~/.dillo/bm.txt -o ~/.dillo/bm.txt.update 2>&1| sed -e "s/.*illegal.*/illegal/g"`

if test "x$CONVTEST" = "xillegal"; then
    rm -f ~/.dillo/bm.txt.update
    echo "** WARNING **: bookmark was broken!"
    for i in `cat ~/.dillo/bm.txt|sed -e "s/ /\\\\\\\\s/g"`; do
        echo $i|sed -e "s/\\\\s/ /g" |LANG=C iconv -f $CHARSET -t UTF-8 2>&1 >> ~/.dillo/bm.txt.update | sed -e "s/.*illegal.*/\\n/g" >> ~/.dillo/bm.txt.update;
    done
else
    echo "update success!"
fi

mv -f ~/.dillo/bm.txt ~/.dillo/bm.txt.old
mv -f ~/.dillo/bm.txt.update ~/.dillo/bm.txt
echo "backup old bookmark as ~/.dillo/bm.txt.old"
