#!/usr/local/cpanel/3rdparty/bin/perl

# cpanel - libexec/cpanel-onboot                   Copyright 2024 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package libexec::cpanelOnboot;

use cPstrict;

use Cpanel::CleanINC ();    # PPI USE OK - this needs to be first

use Cpanel::PIDFile         ();
use Cpanel::SafeRun::Errors ();

use Try::Tiny;

use constant PID_FILE => q[/var/run/cpanel-onboot.pid];

our @dirs_to_check = ( '/usr/local/cpanel/libexec/on_boot', '/var/cpanel/on_boot' );

exit( run(@ARGV) // 0 ) unless caller();

sub run (@args) {

    # acquire the pid lock
    my $pid = Cpanel::PIDFile->new(PID_FILE);

    say "On Boot Handler started";

    foreach my $dir (@dirs_to_check) {
        next unless -d $dir;

        opendir my $fd, $dir or next;

        while ( my $line = readdir($fd) ) {
            next if $line =~ m/^\./;

            my $path = $dir . "/" . $line;
            if ( -x $path ) {
                try {
                    say "On Boot Handler running $path";
                    say Cpanel::SafeRun::Errors::saferunallerrors($path);
                };
            }
        }

        close $fd;
    }

    say "On Boot Handler completed";

    return 0;
}

1;
