#/bin/sh
# convert_bookmark Shell Script
# By: Tyler Riti <fizzboy@mail.utexas.edu>
# Simply converts pre-R3 NetPositive bookmarks into the new R3 format while completely
# ignoring any R3 bookmarks (unless specified to do otherwise).
#
# This script is public domain and carries no warranty of any kind. Use at your own risk.
#
# LIMITATIONS: Currently, this script overwrites anything in the Title attribute so be careful.
# The script makes a backup of your Bookmarks folder so this isn't as bad as it could be.

# The directory that we will be doing our work in
WORKING_DIR=~/config/settings/NetPositive/Bookmarks
# Where we will backup the bookmark folder
BACKUP_DIR=~/config/settings/NetPositive/Bookmarks.BAK
# What the correct mime type should be
NEW_MIME=application/x-vnd.Be-bookmark
# The mime type of the bookmark that we are currently working on
CURRENT_MIME=
# What the mime type shouldn't be
OLD_MIME=application/octet-stream
# Path to the bookmark that we are currently working on
BOOKMARK=
# Name of the bookmark that we are currently working on
NAME=
# Title of the bookmark that we are currently working on
TITLE=
# Url of the bookmark that we are currently working on
URL=
# Name of this script
CMDNAME=`basename $0`
# Usage message
USAGE="Usage: $CMDNAME [-a ]
	-a		Convert all bookmarks, not just old ones"



# backup the bookmark folder
copyattr -r -d "$WORKING_DIR" "$BACKUP_DIR"

# parse command options
while [ $# -gt 0 ]; do
	case $1 in
		-a) addattr -t mime BEOS:TYPE "$OLD_MIME" $WORKING_DIR/*; shift;; # what a kludge!
		--) shift; break;; # end of options
		-*) echo "$USAGE" 1>&2; exit 1;; # print usage
		*) break;; # end of options
	esac
done

echo "Starting..."

for BOOKMARK in $WORKING_DIR/* ; do
	
	CURRENT_MIME=`catattr BEOS:TYPE "$BOOKMARK" | awk -F ' : ' '{print $3}'`
	
	# figure out if we even need to do any work on this bookmark
	if [ "$CURRENT_MIME" != "$NEW_MIME" ]; then
		NAME=`basename "$BOOKMARK"`
		echo "$NAME"
		
		# put the title attribute in the right place
		TITLE=`catattr title "$BOOKMARK" 2>/dev/null | awk -F ' : ' '{print $3}'`
		if [ "$TITLE" != "" ]; then
			if addattr -t string META:title "$TITLE" "$BOOKMARK"; then
				rmattr title "$BOOKMARK"
			fi
		else
			addattr -t string META:title "$NAME" "$BOOKMARK"
		fi
		
		# put the url attribuite in the right place
		URL=`catattr url "$BOOKMARK" 2>/dev/null | awk -F ' : ' '{print $3}'`
		if [ "$URL" != "" ]; then
			if addattr -t string META:url "$URL" "$BOOKMARK"; then
				rmattr url "$BOOKMARK"
			fi
		fi
	fi
done

# add the bookmark mimetype
addattr -t mime BEOS:TYPE "$NEW_MIME" $WORKING_DIR/*

echo "Finished."
#/system/Tracker ~/config/settings/NetPositive
echo "Your old NetPositive bookmark folder is now stored as:"
echo "$BACKUP_DIR"
