#! /usr/bin/env perl
use strict;
use warnings;
use Test::More;
use IPC::System::Simple qw( capture $EXITVAL EXIT_ANY );

use constant {
    INIT_SCRIPT => '/etc/init.d/smcroute',
};

sub get_smcrouted_pid {
    my $expected = shift;

    my $smcroute_pid = capture EXIT_ANY, 'pgrep', 'smcrouted';
    chomp $smcroute_pid;

    if ($expected eq 'running') {
        return $smcroute_pid if $EXITVAL == 0;
    }
    else {
        return $smcroute_pid if $EXITVAL == 1;
    }

    # Retry after one second if pgrep unexpectedly failed or succeeded
    sleep 1;
    $smcroute_pid = capture EXIT_ANY, 'pgrep', 'smcrouted';
    chomp $smcroute_pid;
    return $smcroute_pid;
}

plan tests => 13;

# Work around test harness, start smcrouted if not already running
my $startup = capture EXIT_ANY, INIT_SCRIPT, 'start';
pass($startup);

# Verify that smcroute is running
my $initial_smcroute_pid = get_smcrouted_pid 'running';
is $EXITVAL, 0, "smcroute is running".( $EXITVAL ? '' : " (pid $initial_smcroute_pid)" );

# Try to stop the daemon
my $stop_output = capture EXIT_ANY, INIT_SCRIPT, 'stop';
is $EXITVAL, 0, "stopping smcroute";
my $smcroute_pid = get_smcrouted_pid 'stopped';
is $EXITVAL, 1, "smcroute is really stopped".( $EXITVAL ? '' : " (pid $smcroute_pid)" );
SKIP: {
    skip "System not managed by systemd", 1 unless -e '/run/systemd/system';
    my $wait_output = capture EXIT_ANY, 'systemctl', 'is-system-running', '--wait'; chomp $wait_output;
    is $wait_output, "running", "Stopping smcroute completed";
}

my $double_stop_output = capture EXIT_ANY, INIT_SCRIPT, 'stop';
is $EXITVAL, 0, "stopping smcroute twice in a row";
$smcroute_pid = get_smcrouted_pid 'stopped';
is $EXITVAL, 1, "smcroute is really stopped".( $EXITVAL ? '' : " (pid $smcroute_pid)" );

# Try to start the daemon again
my $start_output = capture EXIT_ANY, INIT_SCRIPT, 'start';
is $EXITVAL, 0, "starting smcroute";
SKIP: {
    skip "System not managed by systemd", 1 unless -e '/run/systemd/system';
    my $wait_output = capture EXIT_ANY, 'systemctl', 'is-system-running', '--wait'; chomp $wait_output;
    is $wait_output, "running", "Starting smcroute completed";
}
my $new_smcroute_pid = get_smcrouted_pid 'running';
is $EXITVAL, 0, "smcroute is really running".( $EXITVAL ? '' : " (pid $new_smcroute_pid)" );
isnt $new_smcroute_pid, $initial_smcroute_pid, "smcroute pid changed ($new_smcroute_pid != $initial_smcroute_pid)";

my $double_start_output = capture EXIT_ANY, INIT_SCRIPT, 'start';
is $EXITVAL, 0, "starting smcroute twice in a row";
$smcroute_pid = get_smcrouted_pid 'running';
is $EXITVAL, 0, "smcroute is really running".( $EXITVAL ? '' : " (pid $smcroute_pid)" );
