Public
Snippet $1655252 authored by Jesse

Check if a restart is needed for a Raspbian kernel update

check-restart.pl
#!/usr/bin/env perl
 
#############################################################################
# File: check-restart.pl
# Language: Perl
# Version: 0
# Author: culb (nightfrog)
# Contact: the01culb[at]gmail[dot]com
#
# Usage: perl check-restart.pl
# Purpuse: Check if a restart is needed for a kernel update
#
# Note: Developed and checked using, Raspbian GNU/Linux 8 (jessie) 4.4.48-v7+
#############################################################################
 
use v5.12;# readdir
use strict;
use warnings;
use File::Spec;
 
my $directory = "/lib/modules";
 
opendir my $dh, $directory or die "Can't open $directory: $!";
 
use constant{ OFF => "\033[0m", RED => "\e[31m" };
 
sub prnt_red{ print RED . $_[0] . OFF; }
 
# Get the running kernel version and remove the newline that uname appends to output
my $kernelVersion = `uname -r`;
$kernelVersion =~ s/\n//;
 
while( my $dirFile = readdir $dh )
{
    if( -d File::Spec->catfile( $directory, $dirFile )
        and $dirFile =~ /\A   # begin
                         \d{1}# 0-9 once
                            \.# decimal
                       \d{1,2}# 0-9 once or twice
                            \.# deciaml
                       \d{1,2}# 0-9 one or twice
               (-v\d{1,2}\+?)?# "-vX+" -v is literal, X is 0-9 once or twice
                              # + is literal and optional, the whole string is optional
                          \Z/x# end
    ){
        if( $dirFile gt $kernelVersion )
        {
            my $tput = `tput colors`;
            print "Kernel update, please restart!\n" if $tput < 8;
            prnt_red "Kernel update, please restart!\n" if $tput >= 8;
        }
        else
        {
            print "No kernel update, restart isn't needed\n";
        }
    }
}
 
closedir $dh;