#!/usr/bin/perl

# needrestart-session - check for processes need to be restarted in user sessions
#
# Authors:
#   Thomas Liske <thomas@fiasko-nw.net>
#
# Copyright Holder:
#   2014 - 2015 (C) Thomas Liske [http://fiasko-nw.net/~thomas/]
#
# License:
#   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 package; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

use Net::DBus;
use Net::DBus::Service;
use Net::DBus::Reactor;
use Sys::Syslog qw(:standard :macros);
use POSIX ":sys_wait_h";
use NeedRestart;

use warnings;
use strict;

$0 = q(needrestart-dbus-session);

BEGIN {
    openlog(q(needrestart-dbus-session), 'pid', LOG_USER);
}

END {
    syslog(LOG_INFO, q(terminated));
}

sub WARN_handler {
    my $signal = shift;
    syslog(LOG_WARNING, q(%s), $signal);
}

sub DIE_handler {
    my $signal = shift;
    syslog(LOG_ERR, q(%s), $signal);
    exit;
}

$SIG{__WARN__} = q(WARN_handler);
$SIG{__DIE__}  = q(DIE_handler);

syslog(LOG_INFO, q(%s %s launched), $0, $NeedRestart::VERSION);

my $bus = Net::DBus->system();

# Net::DBUS seems to be buggy in service activation, trigger
# service activation manually.
$bus->get_bus_object->StartServiceByName(q(net.ibh.NeedRestart.System), 0);

my $service = $bus->get_service(q(net.ibh.NeedRestart.System));
my $object  = $service->get_object(q(/net/ibh/NeedRestart/System),
				   q(net.ibh.NeedRestart.System));

my $nx11pid;
$SIG{CHLD} = sub {
    while( (my $pid = waitpid(-1, WNOHANG)) > 0 ) {
	$nx11pid = undef if($nx11pid == $pid);
    }
};

sub hNotifySessions {
    if(defined($nx11pid)) {
	syslog(LOG_INFO, q(received NotifySession signal but needrestart-session is already alive));
	kill(q(USR1), $nx11pid);
	return;
    }

    syslog(LOG_INFO, q(received NotifySession signal));

    $nx11pid = fork();
    unless(defined($nx11pid)) {
	syslog(LOG_ERR, q(Unable to fork!));
	return;
    }

    if($nx11pid == 0) {
	exec(qw(needrestart-session -n));
	die(q(Unable to exec '/usr/bin/needrestart-session -n'!));
    }
}

my $sig = $object->connect_to_signal(q(NotifySessions), \&hNotifySessions);

my $reactor = Net::DBus::Reactor->main();

syslog(LOG_INFO, q(entering event loop...));
$reactor->run();
syslog(LOG_INFO, q(leaving event loop));
