: # use perl
    eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;
# Above construction is a generic way will find perl if it is in the path.
#################################################################################################
#################################################################################################
###  ------------------------------  unibook V 0.9 -------------------------------            ###
###  (C) by Alain Brenzikofer   							      ###
###											      ###
###  Script to manage Netscape and Opera Bookmarks with a remote mysql table		      ###
###  This is real roaming.....								      ###
###											      ###
###  You may use and change this script like you want.					      ###
###  If you have improvements, please mail me: brenzi@student.ethz.ch			      ###
###											      ###
#################################################################################################
# use lib '/usr/pack/mysql-3.22.32-to/perl/solaris';
use DBI;

########################### get arguments #############
	
	while ($#ARGV >= 0) {
	   $argument=shift;
	   if ($argument =~ /^-up$/) {$upload=true;}
	   elsif ($argument =~ /^-down$/) {$download=true;}
	   if ($argument =~ /^(-op|-opera)$/) {$oponly=true;}
	   elsif ($argument =~ /^(-ns|-netscape)$/) {$nsonly=true;}
	   
	   #if ((!$upload)&&(!$download)) {&usage;}
	}
	unshift(@ARGV,@files);

############################ get preferences ###########

	$filename = ".unibook";
	open(CONF, "<$filename") || die "can't open datafile: $!";
	
	while(($tmp=<CONF>)&&($tmp=~ m/#/)) {;}	# skip comment lines
	$file_netscape = $tmp;
	while(($tmp=<CONF>)&&($tmp=~ m/#/)) {;}	# skip comment lines
	$file_opera = $tmp;
	while(($tmp=<CONF>)&&($tmp=~ m/#/)) {;}	# skip comment lines
	$f_account = $tmp;   
	while(($tmp=<CONF>)&&($tmp=~ m/#/)) {;}	# skip comment lines
	$tablename = $tmp;   
	
	close(CONF);
	
	chop $file_netscape;
	chop $file_opera;
	chop $f_account;
	chop $tablename;
		
	
####################### reading mysql account data ########

	$filename = "/home/brenzi/mysql/mysql.dat";
	#$filename = "/home/brenzala/protected/mysql.dat";
	open(INFO, "<$f_account") || die "can't open datafile: $!";
	$hostname = <INFO>;
	$database = <INFO>;
	$username = <INFO>;
	$password = <INFO>;
	close(INFO);
	
	chop $hostname;
	chop $database;
	chop $username;
	chop $password;
	$hostname = 'DBI:mysql:' . $database . ':' . $hostname;
	
	# opening database connection
	$dbh = DBI->connect($hostname, $username, $password) or die $DBI::errstr;

########################## switch to desired action ########

	if ($upload) 
	{
		print "ready to upload\n";
		print "Getting remote data  \n";	#to compare with new data
		$sth = $dbh->prepare("SELECT name, url, cat FROM $tablename ") || die "Couldn't prepare statement: " . $dbh->errstr;
		$sth->execute() || die "Couldn't execute statement: " . $sth->errstr;
		while (@row = $sth->fetchrow_array())
		{
			push(@remotedata, @row[0].@row[1].@row[2]);
		}	
		print "\b\n";	
		
		#### upload netscape data
		if (!$oponly)
		{
		  open(INPUT, "<$file_netscape") || die "can't open datafile: $!";
  
  		  $fcount = 0;
  		  $ucount = 0;
  		  &dive_netscape('root');
		  close(INPUT);
		  print "\nAdded URLs by Netscape: $ucount and FOLDERs: $fcount \n\n";
		}
		
		#### upload opera data		
		if (!$nsonly)
		{
		  open(INPUT, "<$file_opera") || die "can't open datafile: $!";

		  $fcount = 0;
		  $ucount = 0;
		  &dive_opera('root');
		  close(INPUT);
		  print "\nAdded URLs by Opera: $ucount and FOLDERs: $fcount \n\n";
		}  
	}
	elsif ($download) 
	{
		print "ready to download \n";
		#open bookmark files
		if (!$oponly) {open(OUTPUTns, ">$file_netscape") || print "can't write output datafile: $!";}
		else {open(OUTPUTns, ">/dev/null") || print "can't write output datafile: $!";}
		if (!$nsonly) {open(OUTPUTop, ">$file_opera") || print "can't write output datafile: $!";}
		else {open(OUTPUTop, ">/dev/null") || print "can't write output datafile: $!";}

		$fcount = 0;
		$ucount = 0;
		
		#file header
		print OUTPUTns "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<TITLE>universal bookmarks</TITLE>\n<H1>unibook</H1>\n";
		print OUTPUTop "Opera Hotlist version 2.0\n\n";
	
	
		&dive_up('root');
		
		close(OUTPUTns);
		close(OUTPUTop);

		print "URLs: $ucount - FOLDERs: $fcount ";
	
			
	}
	else {&usage;}

 # disconnect from database
 $dbh->disconnect;
exit;





###############################################################################################################
############################################    routines     ##################################################
###############################################################################################################



sub dive_netscape
{
	my $path	= $_[0];
	print "/// pushing /// ".$path."\n";
	while(<INPUT>) {
		my $tmp= $_;
		# new subdirectory?
		if ($tmp =~ m/<\/DL>/i) { return; }
		if (($tmp =~ m/<H3/i)&&($' =~ m/>/))		# suche <H3 ....> Tag				######Verzeichnis
		{ 	
			$'=~ m/</;	#suche das Ende des Ordnernamens		
			my $dirname = $`;
			
			# update unibook
			if (!checkexist($dirname,"dir",$path))
			{
				# insert data into database
			        my $sql = 'REPLACE INTO bookmarks VALUES (NULL, '.$dbh->quote($dirname).', \'dir\', \' \', '.$dbh->quote($path).',NULL, \'no\')';
	      			$sth = $dbh->prepare($sql) || die "Couldn't prepare statement: " . $dbh->errstr;
	      			$sth->execute() || die "Couldn't execute statement: " . $sth->errstr;
	      			$fcount += 1;
			}
			&dive_netscape($path . "/" . $`);
		}
		if ($tmp =~ m/HREF="/i)																								#####Link
		{
			$'=~ m/"/;  #Ende des Links "
			my $url = $`;
			$'=~ m/>/;
			$'=~ m/</;
			my $name = $`;
			print OUTPUT "$counter \t $name \t $url \t \t $path \t \t \n";
			if (!checkexist($name,$url,$path))
			{
				# insert data into database
	      			my $sql = 'REPLACE INTO bookmarks VALUES (NULL, '.$dbh->quote($name).', '.$dbh->quote($url).', \' \', '.$dbh->quote($path).',NULL, \'no\')';
	      			$sth = $dbh->prepare($sql) || die "Couldn't prepare statement: " . $dbh->errstr;
	      			$sth->execute() || die "Couldn't execute statement: " . $sth->errstr;
				$ucount += 1;
			}
			#print "--".$name." - ". $url . "\n";
		}
	}	
	return;
}

sub dive_opera
{
	my $path	= $_[0];
	print "/// pushing /// ".$path."\n";
	while(<INPUT>) {
		my $tmp= $_;
		chomp $tmp;
		# new subdirectory?
		if (($tmp =~ m/-/)&&($` eq '')) { return; }
		if ($tmp =~ m/#FOLDER/i)								######Verzeichnis
		{ 	
			my $tmp = <INPUT>;
			$tmp =~ m/NAME=/i;
			$dirname = clean($');
			#print $dirname."\n";
			# update unibook
			if (!checkexist($dirname,"dir",$path))
			{
				# insert data into database
	      			my $sql = 'REPLACE INTO bookmarks VALUES (NULL, '.$dbh->quote($dirname).', \'dir\', \' \', '.$dbh->quote($path).',NULL, \'no\')';
	      			$sth = $dbh->prepare($sql) || die "Couldn't prepare statement: " . $dbh->errstr;
	      			$sth->execute() || die "Couldn't execute statement: " . $sth->errstr;
	      			$fcount += 1;
			}
			&dive_opera($path . "/" . $dirname);
		}
		if ($tmp =~ m/#URL/i)																								#####Link
		{
			my $tmp = <INPUT>;
			$tmp =~ m/NAME=/i;
			$name = clean($');
			my $tmp = <INPUT>;
			$tmp =~ m/URL=/i;
			$url = clean($');
			#print OUTPUT "$counter \t $name \t $url \t \t $path \t \t \n";
			if (!checkexist($name,$url,$path))
			{
				# insert data into database
	      			my $sql = 'REPLACE INTO bookmarks VALUES (NULL, '.$dbh->quote($name).', '.$dbh->quote($url).', \' \', '.$dbh->quote($path).',NULL, \'no\')';
  			        $sth = $dbh->prepare($sql) || die "Couldn't prepare statement: " . $dbh->errstr;
			        $sth->execute() || die "Couldn't execute statement: " . $sth->errstr;
				$ucount += 1;
			}
			#print "--".$name." - ". $url . "\n";
		}
	}	
	return;
}		
sub checkexist
{
	$value=0;
	foreach $d (@remotedata)
	{
		if ($d eq $_[0].$_[1].$_[2]) { $value=1;}
	}
	return $value;	
}
sub clean
{
	$d=$_[0];
	chomp $d;			#return entf.
	$d =~ s/\r//;	#carriage return entf.
	return $d;
}	


###############
sub dive_up
{
	my $path	= $_[0];
	
	print OUTPUTns "<DL><p>\n";	#enter new level
	
	#get the unibook-part at current level
	my $sql = "SELECT name, url, cat FROM $tablename WHERE (cat=".$dbh->quote($path).")";
	my $sth = $dbh->prepare($sql) || print "Couldn't prepare statement: " . $dbh->errstr;
	$sth->execute() || print "Couldn't execute statement: " . $sth->errstr;
	
	print "/// getting ///".$path."\n";
	while(my @data = $sth->fetchrow_array())
	{
	    if (@data[1] eq "dir") {
			print OUTPUTns "<DT><H3 FOLDED>".@data[0]."</H3>\n";
			print OUTPUTop "#FOLDER\n\tNAME=".@data[0]."\n\tCREATED=990656987\n\tVISITED=0\n\tORDER=0\n\tDESCRIPTION=unibooked\n\n";
			$fcount += 1;
			&dive_up($path . "/" . @data[0]);
	    }
	    else {
			print OUTPUTns '<DT><A HREF="'.@data[1].'">'.@data[0]."</A>\n";
			print OUTPUTop "#URL\n\tNAME=".@data[0]."\n\tURL=".@data[1]."\n\tCREATED=990656987\n\tVISITED=0\n\tORDER=0\n\tDESCRIPTION=unibooked\n\n";
			$ucount += 1;
	    }
	}	
	print OUTPUTns "<\/DL><p>\n";	#enter new level
	print OUTPUTop "-\n\n";

	return;
}	
	



sub usage
{

print STDERR <<EOF;
unibook 0.9
by Alain Brenzikofer

Syntax:  unibook.pl ( -up |-down ) [ -op |-ns ]  

Purpose: Manage your Netscape and Opera bookmarks over all platforms

Details: Your local bookmark files are scanned and all bookmarks are
	 transferred to a remote mysql table.
	 
	 -up	upload your bookmarks to mysql table
	 -down  download and save bookmarks to your Opera and Netscape files
	 
	 -op	or	
	 -opera		only Opera bookmarkfile is used
	 
	 -ns	or
	 -netscape	only netscape file is used

EOF
exit 1;
}
