#!/usr/bin/perl -w

############################################################################
# ed2k_urlslave                                                            #
############################################################################
# Version: 1                                                               #
#                                                                          #
# Author:  Veit Wahlich <cru@ircnet.de>                                    #
#                                                                          #
# Descr.:  Little GTK+ enabled Perl script for adding ed2k:// links to     #
#          ed2k GUI, designed for better ed2k:// URL handling within Gnome #
#          (especially Galeon) but might be used for any other purpose.    #
#                                                                          #
# Syntax:  ed2k_urlslave <ed2k:// url>                                     #
############################################################################
# Setting up ed2k_urlslave and Gnome:                                      #
# 1. Copy ed2k_urlslave to a place in $PATH, I suggest /usr/local/bin/     #
# 2. Start gnomecc and open the URL handler capplet                        #
# 3. Fill in 'ed2k' to the protocol field and 'ed2k_urlslave "%s"' to the  #
#    handler field                                                         #
# 4. Hit 'set' to add the new protocol handler                             #
# 5. Take any Gnome program (e.g. Galeon) and click some ed2k:// URLs ;)   #
############################################################################

$ed2k_gui_socket="/tmp/.ed2k_gui_socket";


my $false=0;
my $true=1;

sub ShowErrWindow{
	init Gtk;
	
	my $window=new Gtk::Window("toplevel");
	my $button=new Gtk::Button("OK");

	$window->signal_connect( "delete_event", \&CloseErrWindow );   
	$button->signal_connect( "clicked", \&CloseErrWindow );

	$window->border_width(15);
	$window->set_title("Error!");
	$window->set_position("center");

	my $label=new Gtk::Label("An error occured while adding your ed2k:// URL to the ed2k GUI: \n\n".$_[0]."\n\n");
	$label->set_line_wrap($true);

	my $vbox=new Gtk::VBox($false,0);
	$vbox->pack_start($label,$false,$false,$false);
	$vbox->pack_start($button,$false,$false,$false);

	$window->add($vbox);
	$window->show_all();

	main Gtk;
	exit;
}

sub CloseErrWindow{
   Gtk->exit(0);
   return $false;
}

sub AppMain{
	if(lc(substr(&args(),0,7)) ne "ed2k://"){
		if(&args()){
			&ShowErrWindow("The URL submitted does not seem to be a ed2k:// URL!");
		}else{
			&ShowErrWindow("No URL submitted!");
		}
	}elsif(-e $ed2k_gui_socket){
		open(SOCK,">".$ed2k_gui_socket)||&ShowErrWindow("Unable to push URL to ed2k GUI socket:\n".$!);
		print SOCK &args()."\n";
		close(SOCK);
	}else{
		&ShowErrWindow("ed2k GUI seems not to be running!");
	}
}

sub args{
	return join(" ",@ARGV);
}

use Gtk;
use strict;

&AppMain();
exit(0);