#!/bin/bash

# 2021-02-05 Clean up old kernels on Linux Mint. This needs rm -f as
# we usually need this to free up space on the root filesystem.

# by teknohog

CUR=$(uname -r)

# Time reference file
REF=/boot/vmlinuz-$CUR

[ -f $REF ] || exit

# Time reference
REFTIME=$(date +%s -r $REF)

# Add some safety margin, don't just use [ file1 -ot file2 ]
REFTIME=$((REFTIME - 86400))

cd /boot

for FILE in vmlinuz* config* initrd* System.map*; do
    # initrd might not exist
    [ -f $FILE ] || continue
    
    # Remove kernels older than the current, as we may have newer ones
    # installed.

    MTIME=$(date +%s -r $FILE)

    if [ $MTIME -lt $REFTIME ]; then
	echo Deleting /boot/$FILE
	rm -f $FILE
    fi
done

cd /lib/modules

for DIR in *; do
    MTIME=$(date +%s -r $DIR)

    if [ $MTIME -lt $REFTIME ]; then
	echo Deleting /lib/modules/$DIR
	rm -rf $DIR
    fi
done


