#!/usr/bin/perl -w
#    GNU Public License (GPL)
#
#    Copyright (c) 2010-14 Stéphane GALLAND <galland@arakhne.org>
#
#    This program is free software; you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by the
#    Free Software Foundation; either version 2 of the License, or (at your
#    option) any later version.
#
#    This program is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#    Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; see the file COPYING. If not, write to the Free
#    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
#    02111-1307, USA.

use strict;

#--------------------------------------------------------------

use constant VERSION => '8.2';
use constant APPNAME => 'kernel-cleaner-gtk2';

#--------------------------------------------------------------

use threads qw(yield);
use threads::shared;
use Gtk2::TrayIcon;
use File::Basename;
use File::Spec;
use Getopt::Long;



#--------------------------------------------------------------

use constant TRUE => 1;
use constant FALSE => 0;
use constant MAIN_NO_ICON => '/usr/share/icons/kernelcleaner_no.png';
use constant MAIN_NO_ICON2 => File::Spec->catfile(dirname($0),'kernelcleaner_no.png');
use constant MAIN_YES_ICON => '/usr/share/icons/kernelcleaner_yes.png';
use constant MAIN_YES_ICON2 => File::Spec->catfile(dirname($0),'kernelcleaner_yes.png');
use constant MAIN_RM_ICON => '/usr/share/icons/kernelcleaner_rm.png';
use constant MAIN_RM_ICON2 => File::Spec->catfile(dirname($0),'kernelcleaner_rm.png');
use constant CLEANER_CMD => '/usr/sbin/kernel-cleaner';
use constant CLEANER_CMD2 => File::Spec->catfile(dirname($0),'kernel-cleaner');

#--------------------------------------------------------------

use POSIX qw(setlocale);
use Locale::gettext;

{
	my $LANG_DIRECTORY;
	my $sourceDir = dirname($0);
	if (-r File::Spec->catfile($sourceDir, 'po', 'fr', 'LC_MESSAGES', 'kernel-cleaner-gtk2.mo')) {
		$LANG_DIRECTORY = File::Spec->rel2abs(File::Spec->catfile($sourceDir, 'po'));
	}
	else {
		$sourceDir = dirname($sourceDir);
		if (-r File::Spec->catfile($sourceDir, 'po', 'fr', 'LC_MESSAGES', 'kernel-cleaner-gtk2.mo')) {
			$LANG_DIRECTORY = File::Spec->rel2abs(File::Spec->catfile($sourceDir, 'po'));
		}
		else {
			$LANG_DIRECTORY = '/usr/share/locale';
		}
	}
	setlocale(LC_ALL, "");
	bindtextdomain(APPNAME, $LANG_DIRECTORY);
	textdomain(APPNAME);
}

sub _T {
	return gettext(@_);
};

#--------------------------------------------------------------

my $quitApplet : shared;
my %cmdlineOptions = ();
my $removable = FALSE;

$quitApplet = FALSE;

sub usage() {
    print _T("usage:")."\n";
    print "\t".APPNAME." [--version] [--show]\n";
    exit(1);
}

sub validateUnitySysTray() {
	my $tab;
	eval('$tab = '.`gsettings get com.canonical.Unity.Panel systray-whitelist`.';');
	my @tab = @{$tab};
	foreach my $e (@tab) {
		if ($e eq APPNAME) {
			return;
		}
	}
	push @tab, APPNAME;
	my $str = '';
	foreach my $e (@tab) {
		if ($str) {
			$str .= ", ";
		}
		$str .= "'".$e."'";
	}
	$str = "[$str]";
	system('gsettings set com.canonical.Unity.Panel systray-whitelist "'.$str.'"');
}

#--------------------------------------------------------------

if (!GetOptions('show' => \$cmdlineOptions{'show'},
                'version' => \$cmdlineOptions{'version'})) {
	usage();
	exit(2);
}

if ($cmdlineOptions{'version'}) {
	print VERSION."\n";
	exit(0);
}

validateUnitySysTray();

Gtk2->init;

my $trayicon = Gtk2::TrayIcon->new("KernelCleaner");
my $eventbox = Gtk2::EventBox->new();
my $button = Gtk2::Image->new();
$eventbox->add($button);
$trayicon->add($eventbox);
my $cleanThread;

#--------------------------------------------------------------

sub quitApplet {
	$quitApplet = TRUE;
}

sub cleanKernels {
	my $iconfile;
	if (-r MAIN_RM_ICON2) {
		$iconfile = MAIN_RM_ICON2;
	}
	else {
		$iconfile = MAIN_RM_ICON;
	}
	$button->set_from_file("$iconfile");

	$cleanThread = threads->create (sub {
		#sleep(5);
		system('gksudo', '--sudo-mode', '--', CLEANER_CMD, '--remove');
		quitApplet();
	});
}

sub onClick {
	my ($widget, $event, $data) = @_;
	# Simple click
	if (!$cleanThread && $event && ($event->type() eq 'button-press')) {
		if ($event->button == 1) { # left button
			cleanKernels();
			return TRUE;
		}
		elsif ($event->button == 3) { # right button
			my $menu = Gtk2::Menu->new();

			# Clean menu item
			my $menu_clean = Gtk2::ImageMenuItem->new_with_label(_T("Remove the old kernels of Linux"));
			$menu_clean->set_image(Gtk2::Image->new_from_stock('gtk-delete', 'menu'));
			$menu_clean->signal_connect('activate' => \&cleanKernels);
			$menu->add($menu_clean);

			# Quit menu item
			my $menu_quit = Gtk2::ImageMenuItem->new_with_label(_T("Exit"));
			$menu_quit->set_image(Gtk2::Image->new_from_stock('gtk-close', 'menu'));
			$menu_quit->signal_connect('activate' => \&quitApplet);
			$menu->add($menu_quit);

			#popup menu, the three is for right mouse button
			$menu->show_all;
			$menu->popup(undef,undef,undef,3,3,0);

			return TRUE;
		}
	}
	return FALSE;
}

#--------------------------------------------------------------

my $cmd;
if (-x CLEANER_CMD2) {
	$cmd = CLEANER_CMD2;
}
else {
	$cmd = CLEANER_CMD;
}
system("$cmd", '--testremove');
$removable = ($? == 0);

if ($removable || $cmdlineOptions{'show'}) {
	my $iconfile;
	if ($removable) {
		if (-r MAIN_YES_ICON2) {
			$iconfile = MAIN_YES_ICON2;
		}
		else {
			$iconfile = MAIN_YES_ICON;
		}
	}
	else {
		if (-r MAIN_NO_ICON2) {
			$iconfile = MAIN_NO_ICON2;
		}
		else {
			$iconfile = MAIN_NO_ICON;
		}
	}
	$button->set_from_file("$iconfile");
	$eventbox->signal_connect('button-press-event', \&onClick);
	$trayicon->show_all;

	#Gtk2->main;
	while ((!$quitApplet) && Gtk2->main_iteration_do(FALSE)) {
		yield();
	}

	if ($cleanThread) {
		$cleanThread->join();
	}
}

exit(0);
