#!/usr/bin/perl
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell





## 
## Convert a firefox bookmarks.html file into a elinks native bookmark file
## USAGE:
##	firefox2elinks.pl [--i=infile] [--o=outfile]
## 
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
## 
## firefox bookmark format
## 
## 
## <DL> enter folder
## <DT> entry - URL(<A HREF>), folder(<H3>)
## </DL> exit folder
## 
## 
## 
## elinks bookmark format
## 
## folder \t \t N \t F - N is level of folder root N=0, folder in folder N=1
## bookmark name \t URL \t M - M is level from root M=N+1, root bm M=1, in 1 folder M=2, 2; M=2
## 



use strict;
use warnings;
use Getopt::Long;
use File::Copy;






## find standard elinks/firefox bookmarks to use if
## nothing is specified
my $inputfile = `find $ENV{HOME}/.mozilla/firefox -name 'bookmarks.html'`;
chomp($inputfile);
my $outputfile = "$ENV{HOME}/.elinks/bookmarks";

my $argret=GetOptions(
		      "i=s" => \$inputfile,
		      "o=s" => \$outputfile,
		     );


print "\nConverting firefox bookmarks \"$inputfile\"\n".
	"\tto elinks standard bookmarks \"$outputfile\".....\n";


my $start_of_bm = 1;
my $folder_counter = 0;



## copy current elinks.conf file if it exists
if(-e $outputfile) {
	print ".... Copying \"$outputfile\" to \"$outputfile.orig\"....\n";
	copy($outputfile, "$outputfile.orig")
		or die "Cannot copy $outputfile\n";
}



## open firefox bm to read and elinks bm to write to
open(IN, "$inputfile") or die "cannot open $inputfile: $!";
open(OUT, ">$outputfile") or die "cannot open $outputfile: $!";
while(<IN>) {

    if(/<HR>/)   { $start_of_bm = 0; }


    ## don't start parsing until past the horizontal rule
    if(!$start_of_bm) {

	## count folders that are moved into and out of
	if(/<DL>/)   { $folder_counter++; }
	if(/<\/DL>/) { $folder_counter--; }



	## match folder title
	if (/<H[0-9]/) {
	    s/.*?<H[0-9].*?>(.*?)<//;
	    print OUT "$1\t\t${folder_counter}\tF\n";
	}


	## match bookmark url
	if (/<A HREF/) {
	    s/.*?<A HREF="(.*?)".*?>(.*?)<//;
	    print OUT "$2\t$1\t${folder_counter}\n";
	}
    }

}
## close opened files
close(IN);
close(OUT);


print "\tConversion complete\n\n";
