#!/usr/bin/perl
package autofixer2::multiple_tailwatchd;

# cpanel - autofixer2/multiple-tailwatchd         Copyright(c) 2016 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

use strict;

BEGIN { unshift @INC, '/usr/local/cpanel'; }

use Cpanel::PsParser ();

sub tailwatch_pids {
    my $ps = Cpanel::PsParser::fast_parse_ps();
    return map { $_->{'pid'} } grep { $_->{'command'} eq 'tailwatchd' } @$ps;
}

sub is_affected {
    return tailwatch_pids() > 1;
}

sub signal {
    my ($sig) = @_;
    my @pids = tailwatch_pids();
    return unless @pids;
    kill( $sig, @pids );
    return 1;
}

sub fix {
    for ( 1 .. 3 ) {
        signal('TERM') or last;
        sleep(1);
    }
    signal('KILL');
    system('/usr/local/cpanel/scripts/restartsrv_tailwatchd');
    return !is_affected();
}

sub script {
    return 0 unless is_affected();

    my $is_fixed = fix();
    print "Multiple tailwatchd processes were killed.\n";
    print "tailwatchd has been restarted.\n";
    return !$is_fixed;
}

exit script() unless caller;
