#!/bin/sh

PATH=/opt/csw/bin:/opt/local/bin:/usr/bin:/bin exec perl -w -x "$0" "$@"

#!perl

use strict;
use warnings FATAL => 'all';

use Glib qw/TRUE FALSE/;
use Gtk2 '-init';
use Gtk2::Gdk::Keysyms;
use LWP::UserAgent;

my %g_key = ();
my %g_arrows;
my $g_host = Gtk2::ComboBox->new_text();
my $g_identity = Gtk2::ComboBox->new_text();
my $ua = LWP::UserAgent->new;

open(INIFILE,"<$ENV{HOME}/.snomrc") || die("can't open config: $ENV{HOME}/.snomrc: $!");
my %Config = ();
my @sections = ();
while(<INIFILE>) {
	chomp;

	next if (m/^#/);
	
	if (m/^\s*\[(.*)\]\s*$/) {
		push @sections, $1;
		next;
	}

	if (@sections) {
		if (m/^\s*(.+)\s*=\s*(.*)\s*$/) {
			${$Config{$sections[$#sections]}}{$1} = $2;
		}
	}
}
close(INIFILE);

for my $section (@sections) {
	if (defined(${$Config{$section}}{host})) {
		$g_host->append_text($section);
		if (defined(${$Config{$section}}{login}) &&
			defined(${$Config{$section}}{password})) {
			$ua->credentials(${$Config{$section}}{host}.":80",
				"snom",
				${$Config{$section}}{login},
				${$Config{$section}}{password});
		}
	}
}
$g_host->set_active(0);
UpdatePhoneInfo();
$g_host->signal_connect(changed => \&UpdatePhoneInfo);
$g_host->show() if($#sections);
$g_identity->signal_connect(changed => \&SwitchIdentity);

set_locale Gtk2;

sub snom_key {
	my $key = shift;
	$key='%23' if ($key eq '#');
	my $req = HTTP::Request->new(GET => "http://".${$Config{$sections[$g_host->get_active]}}{host}."/command.htm?key=${key}");
	$ua->request($req);
}

sub snom_number {
	my $number = shift;
	$number =~ s/[^\d]//g;
	my $req = HTTP::Request->new(GET => "http://".${$Config{$sections[$g_host->get_active]}}{host}."/command.htm?number=${number}");
	$ua->request($req);
}

sub gen_table {
	my $rows = shift;
	my $cols = shift;
	my $homogeneous = shift;
	my $row_spacing = shift;
	my $col_spacing = shift;
	my $keys = shift;

	my $table = Gtk2::Table->new($rows, $cols, $homogeneous);
	$table->set_row_spacings($row_spacing);
	$table->set_col_spacings($col_spacing);

	my $n = 0;
	foreach my $key (@$keys) {
		if ($key ne '_') {
			if($key=~m/^ARROWS(.*)$/) {
				$g_key{$key} = Gtk2::Button->new;
				$g_key{$key}->add($g_arrows{"${1}"});
			} else {
				$g_key{$key} = Gtk2::Button->new("${key}");
			}
			$g_key{$key}->signal_connect(clicked => \&KeyPressed, $key);
			$table->attach_defaults($g_key{$key}, (($n)%$cols), (($n)%$cols)+1, int(($n)/$cols), int((($n)/$cols)+1));
			$g_key{$key}->show();
		}
		$n++;
	}

	$table->show();

	$table;
}

my $window = Gtk2::Window->new('toplevel');
$window->set_title("snom");
$window->signal_connect(delete_event => \&CloseAppWindow);   
$window->signal_connect(destroy => sub { Gtk2->main_quit; });
my $kphandler = $window->signal_connect(key_press_event => \&KBDInput);
$window->set_border_width(15);
$window->set_resizable(FALSE);

my $keypad = gen_table(4, 3, TRUE, 2, 2, [1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#']);

my $fkeys = gen_table(6, 2, TRUE, 2, 2, 
	['_Redial', 'S_ettings', 'Director_y', 'Hel_p', 'Men_u', 'snom', '_', '_',
	'_Conference', '_Transfer', 'H_old', '_DND']);

my $pkeys = gen_table(6, 2, TRUE, 2, 2, ['P1', 'P7', 'P2', 'P8', 'P3', 'P9', 'P4',
	'P10', 'P5', 'P11', 'P6', 'P12']);

my $softkeys = gen_table(1, 4, FALSE, 0, 6, ['F1', 'F2', 'F3', 'F4']);

$g_arrows{up} = Gtk2::Arrow->new('up', 'none');
$g_arrows{up}->show();
$g_arrows{down} = Gtk2::Arrow->new('down', 'none');
$g_arrows{down}->show();
$g_arrows{left} = Gtk2::Arrow->new('left', 'none');
$g_arrows{left}->show();
$g_arrows{right} = Gtk2::Arrow->new('right', 'none');
$g_arrows{right}->show();

my $navi = gen_table(3, 5, FALSE, 0, 0,
	['_', '_', 'ARROWSup', '_', '_', 'X', 'ARROWSleft', '_', 'ARROWSright', 'OK', '_', '_', 'ARROWSdown', '_', '_']);

my $output = gen_table(2, 3, FALSE, 2, 2, ['-', '+', '_', '_Mute', '_Speaker', '_Headset']);

my $special = gen_table(1, 2, FALSE, 0, 2, ['Record', 'Retrieve']);

my $display = Gtk2::Entry->new();
$display->signal_connect(activate => \&DialNumber);
my $kph_blocked = FALSE;
$display->signal_connect(enter_notify_event => \&DisplayMouseOver, TRUE);
$display->signal_connect(leave_notify_event => \&DisplayMouseOver, FALSE);
$display->show();

my $cbextern = Gtk2::CheckButton->new("extern");
$cbextern->show();

my $dialbox = Gtk2::HBox->new(0, 30);
$dialbox->pack_start($display, 0, 0, 0);
$dialbox->pack_start($cbextern, 0, 0, 0);
$dialbox->show();

my $dispbox = Gtk2::VBox->new(0, 5);
$dispbox->pack_start($dialbox, 0, 0, 0);
$dispbox->pack_start($softkeys, 0, 0, 0);
$dispbox->pack_start($navi, 0, 0, 0);
$dispbox->show();

my $outbox = Gtk2::VBox->new(0, 0);
$outbox->pack_start($g_host, 0, 0, 0);
$outbox->pack_end($output, 0, 0, 0);
$outbox->show();

my $specialbox = Gtk2::VBox->new(0, 0);
$specialbox->pack_start($g_identity, 0, 0, 0);
$specialbox->pack_end($special, 0, 0, 0);
$specialbox->show();

my $ubox = Gtk2::HBox->new(0, 30);
$ubox->pack_start($outbox, 0, 0, 0);
$ubox->pack_start($dispbox, 0, 0, 0);
$ubox->pack_start($specialbox, 0, 0, 0);
$ubox->show();


my $kbbox = Gtk2::HBox->new(0, 30);
$kbbox->pack_start($keypad, 1, 1, 0);
$kbbox->pack_start($fkeys, 0, 0, 0);
$kbbox->show();

my $kvbox = Gtk2::VBox->new(0, 5);
$kvbox->pack_end($kbbox, 0, 0, 0);
$kvbox->show();

my $lbox = Gtk2::HBox->new(0, 30);
$lbox->pack_start($kvbox, 1, 1, 0);
$lbox->pack_start($pkeys, 0, 0, 0);
$lbox->show();

my $mainbox = Gtk2::VBox->new(0,5);
$mainbox->pack_start($ubox, 0, 0, 0);
$mainbox->pack_start($lbox, 0, 0, 0);
$mainbox->show();



#########################################################
#
#     Tray Icon
#
#########################################################
sub quit_cb {
   my ($widget, $status_icon) = @_;
 
   $status_icon->set_visible(0) if $status_icon;
   Gtk2->main_quit();
}

sub popup_menu_cb {
   my ($widget, $button, $time, $menu) = @_;

   if ($button == 3) {
   	  my ($x, $y, $push_in)
         = Gtk2::StatusIcon::position_menu($menu, $widget);

     	$menu->show_all();
     	$menu->popup( undef, undef,
             sub{return ($x,$y,0)} ,
             undef, 0, $time );
   }
}

sub activate_icon_cb {
	if ($window->visible){
		$window->hide();
	} else {
		$window->show();
	}
}

my $status_icon = Gtk2::StatusIcon->new_from_file('snom.ico');
my $menu = Gtk2::Menu->new();

my $menuItem = Gtk2::ImageMenuItem->new_from_stock('gtk-quit');
$menuItem->signal_connect('activate', \&quit_cb, $status_icon);
$menu->append($menuItem);

$status_icon->set_tooltip(" Snom Tray ");
$status_icon->signal_connect('activate', \&activate_icon_cb);
$status_icon->signal_connect('popup-menu', \&popup_menu_cb, $menu);
$status_icon->set_visible(1);
########################################################################333

$window->add($mainbox);
$window->set_icon_from_file('snom.ico');
$window->show();

$g_key{OK}->grab_focus();

# Gtk2 event loop
Gtk2->main;

# Should never get here
exit( 0 );


sub KeyPressed
{
	my ($button, $text) = @_;
	$text=~ s/_//g;
	foreach my $i (1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#',
		'F1', 'F2', 'F3', 'F4',
		'P1', 'P2', 'P3', 'P4', 'P5', 'P6',
		'P7', 'P8', 'P9', 'P10', 'P11', 'P12') {
		if ($i eq $text) {
			snom_key($i);
			return TRUE;
		}
	}

	snom_key("REDIAL") if ( $text eq "Redial" );
	snom_key("SETTINGS") if ( $text eq "Settings" );
	snom_key("F_ADR_BOOK") if ( $text eq "Directory" );
	snom_key("HELP") if ( $text eq "Help" );
	snom_key("MENU") if ( $text eq "Menu" );
	snom_key("SNOM") if ( $text eq "snom" );
	snom_key("CONFERENCE") if ( $text eq "Conference" );
	snom_key("TRANSFER") if ( $text eq "Transfer" );
	snom_key("F_R") if ( $text eq "Hold" );
	snom_key("DND") if ( $text eq "DND" );

	snom_key("MUTE") if ( $text eq "Mute" );
	snom_key("SPEAKER") if ( $text eq "Speaker" );
	snom_key("HEADSET") if ( $text eq "Headset" );

	snom_key("CANCEL") if ( $text eq "X" );
	snom_key("ENTER") if ( $text eq "OK" );
	snom_key("UP") if ( $text eq "ARROWSup" );
	snom_key("DOWN") if ( $text eq "ARROWSdown" );
	snom_key("LEFT") if ( $text eq "ARROWSleft" );
	snom_key("RIGHT") if ( $text eq "ARROWSright" );

	snom_key("F_REC") if ( $text eq "Record" );
	snom_key("F_RETRIEVE") if ( $text eq "Retrieve" );

	snom_key("VOLUME_UP") if ( $text eq "+" );
	snom_key("VOLUME_DOWN") if ( $text eq "-" );
	return TRUE;
}

sub DialNumber
{
	my ($entry) = @_;
	my ($num) = $entry->get_text();
	if ($cbextern->get_active){
	 snom_number("09".$num)
	} else {
	 snom_number($num);
	}	
	return TRUE;
}

sub DisplayMouseOver
{
	my ($widget, $event, $active) = @_;

	if ($active) {
		$widget->grab_focus();
		if (!$kph_blocked) {
			$window->signal_handler_block($kphandler);
			$kph_blocked=TRUE;
		}
	} else {
		$g_key{OK}->grab_focus();
		if ($kph_blocked) {
			$window->signal_handler_unblock($kphandler);
			$kph_blocked=FALSE;
		}
	}

	return TRUE;
}

sub KBDInput
{
	my ($widget, $event) = @_;

	my $keyval = $event->keyval;

	for (my $i=0; $i<10; $i++) {
		if ($keyval == $Gtk2::Gdk::Keysyms{$i} || $keyval == $Gtk2::Gdk::Keysyms{"KP_${i}"}) {
			snom_key($i);
			return TRUE;
		}
	}

	if (!$event->state || !($event->state & "control-mask" || $event->state & "mod1-mask")) {
		if ($keyval == $Gtk2::Gdk::Keysyms{asterisk}) {snom_key('*'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Multiply}) {snom_key('*'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{numbersign}) {snom_key('#'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Add}) {snom_key('VOLUME_UP'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{plus}) {snom_key('VOLUME_UP'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Subtract}) {snom_key('VOLUME_DOWN'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{minus}) {snom_key('VOLUME_DOWN'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Return}) {snom_key("ENTER"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Enter}) {snom_key("ENTER"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Escape}) {snom_key("CANCEL"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Left}) {snom_key("LEFT"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Left}) {snom_key("LEFT"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Right}) {snom_key("RIGHT"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Right}) {snom_key("RIGHT"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Up}) {snom_key("UP"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Up}) {snom_key("UP"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Down}) {snom_key("DOWN"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{KP_Down}) {snom_key("DOWN"); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{M}) {snom_key('MUTE'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{m}) {snom_key('MUTE'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{S}) {snom_key('SPEAKER'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{s}) {snom_key('SPEAKER'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{H}) {snom_key('HEADSET'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{h}) {snom_key('HEADSET'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{C}) {snom_key('CONFERENCE'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{c}) {snom_key('CONFERENCE'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{T}) {snom_key('TRANSFER'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{t}) {snom_key('TRANSFER'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{O}) {snom_key('F_R'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{o}) {snom_key('F_R'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{D}) {snom_key('DND'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{d}) {snom_key('DND'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{R}) {snom_key('REDIAL'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{r}) {snom_key('REDIAL'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{E}) {snom_key('SETTINGS'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{e}) {snom_key('SETTINGS'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{Y}) {snom_key('F_ADR_BOOK'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{y}) {snom_key('F_ADR_BOOK'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{P}) {snom_key('HELP'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{p}) {snom_key('HELP'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{U}) {snom_key('MENU'); return TRUE;}
		if ($keyval == $Gtk2::Gdk::Keysyms{u}) {snom_key('MENU'); return TRUE;}
	}

	if (!$event->state) {
		for (my $i=1; $i<5; $i++) {
			if ($keyval == $Gtk2::Gdk::Keysyms{"F${i}"}) {
				snom_key("F${i}");
				return TRUE;
			}
		}
	} else {
		if ($event->state & "mod1-mask") {
			for (my $i=1; $i<13; $i++) {
				if ($keyval == $Gtk2::Gdk::Keysyms{"F${i}"}) {
					snom_key("P${i}");
					return TRUE;
				}
			}
		}
	}

	print "Unhandled: Modifier: ".$event->state.", Key: ";
	foreach my $key (keys(%Gtk2::Gdk::Keysyms)) {
		if ($keyval == $Gtk2::Gdk::Keysyms{$key}) {
			print "${key}\n";
			return TRUE;
		}
	}
	print "ERR\n";
	return FALSE;
}

sub UpdatePhoneInfo
{
	my $req = HTTP::Request->new(GET => "http://".${$Config{$sections[$g_host->get_active]}}{host}."/");
	my $response = $ua->request($req);
	
	$g_identity->set_active(0);
	while($g_identity->get_active() == 0) {
		$g_identity->remove_text(0);
		$g_identity->set_active(0);
	}
	my @lines=split("\n", $response->content());
	my $num = 0;
	my $activated = 0;

	foreach (@lines) {
		chomp;
		#<option value="1" selected>51@stargate.gernoth.loc</option>
		#<option value="2">89@asterix.ear-projekt.de</option>
		#<option value="3">41@grumpy.gernoth.loc</option>
		if (m/^\<option value=\"(.+)\"( selected)?\>([^<\@]*)\@([^<]*)\<\/option\>\s*$/) {
			my $line = $3;
			$g_identity->append_text("${3}");
			if (defined($2)) {
				$g_identity->set_active(${1}-1);
				$activated=1;
			}
			$num++;
		}
	}
	$g_identity->set_active(0) if (!$activated);
	if ($num > 1) {
		$g_identity->show;
	} else {
		$g_identity->hide;
	}
}

sub SwitchIdentity
{
	my $req = HTTP::Request->new(GET => "http://".${$Config{$sections[$g_host->get_active]}}{host}."/dummy.htm?SETTINGS=Set&active_line=".($g_identity->get_active+1));
	$ua->request($req);
}

sub CloseAppWindow
{
	$window->destroy;
	return TRUE;
}
