#!/usr/bin/perl
#
#  bookmark.pl - parses netscape's bookmark file into Window Maker
#  popup menu definitions.
#
#  Brian Martin (briam@cats.ucsc.edu)
#
#  This script is GPL
#
#  options:
#
#    -b bookmarkfile    - specifies location of bookmark file
#                         defaults to $HOME/.netscape/bookmarks.html
#
#    -m max_title_chars - restricts URL titles to this many characters total
#                         excess will be chopped out of middle
#                         defaults to 30
#
#    -T title           - sets title of main bookmark menu
#                         defaults to 'Bookmarks'
#
#    -u url opener      - program to call to open urls
#                         defaults to goto_url
#
#
#  note:  for portability it's best to invoke this script with perl explicitly
#         i.e. use:
#
#         perl wmbookmark.pl
#
#         This is because the #! marker hardcodes the location of the perl
#         interpreter, and we can't guarantee that everyone's got it in the 
#         same place
#

$| = 1;				# force autoflush of pipes

while($arg = shift) {
  $bookmarks = shift, next if ($arg eq '-b');
  $max_title_chars = shift, next if ($arg eq '-m');
  $title = shift, next if ($arg eq '-T');
  $url_opener = shift, next if ($arg eq '-u');
}

$bookmarks = "$ENV{'HOME'}/.netscape/bookmarks.html" unless defined $bookmarks;
$max_title_chars = 30 unless defined $max_title_chars;
$title = "Bookmarks" unless defined $title;
$url_opener = "goto_url" unless defined $url_opener;

open(BOOKMARKS, $bookmarks);

#   entry types : <DL> defines new Popup
#	          <DT> defines new popup entry (of type lin

&get_menu($title);

#print "$ENV{'HOME'}/.netscape/bookmarks.html\n";

close(bookmarks);

sub get_menu {			# parse bookmark file

    local $name = shift;

    print "\"$name\" MENU\n";

    $_ = <BOOKMARKS>;
    
    #read lines until </DL>
    until(m~</DL>~i) {

	if(/<DT>/i) {
	    if( /<a href/i ) {	# link
		@name = split(/\"/);
		@link = split(/[<>]/);
		if(length($link[4]) > $max_title_chars) {
		    $link[4] = substr($link[4], 0, $max_title_chars/2).
		      "...".substr($link[4], -$max_title_chars/2);
		}
		$link[4] =~ s/\"//g;
		print "\"$link[4]\" EXEC $url_opener \"$name[1]\"\n";
	    } else {		# new menu
		@name = split(/[<>]/);
		&get_menu($name[4]);
	    }
	} 
	$_ = <BOOKMARKS>;
    }
    print "\"$name\" END\n";
}





