# vim: ft=perl
use Ubic::Service::Common;
use Ubic::Daemon qw(:all);
use LWP::Simple;
use POSIX;
use Time::HiRes qw(sleep);

use Ubic::Ping;

# ugly; waiting for druxa's Mopheus to save us all...
my $port = $ENV{UBIC_SERVICE_PING_PORT} || 12345;
my $pidfile = $ENV{UBIC_SERVICE_PING_PID} || "/var/lib/ubic/ubic-ping.pid";
my $user = $ENV{UBIC_SERVICE_PING_USER} || 'root';

Ubic::Service::Common->new({
    start => sub {
        my $pid;
        start_daemon({
            bin => qq{perl -MUbic::Ping -e 'Ubic::Ping->new($port)->run;'},
            name => 'ubic-ping',
            pidfile => $pidfile,
        });
    },
    stop => sub {
        stop_daemon($pidfile);
    },
    status => sub {
        unless (check_daemon($pidfile)) {
            return 'not running';
        }
        my $result = get("http://localhost:$port/ping") || '';
        return ((
            $result =~ /^ok$/
        ) ? 'running' : 'broken');
    },
    port => $port,
    user => $user,
    timeout_options => { start => { step => 0.1, trials => 3 }},
});
