2023-09-01 15:42:25 -04:00
|
|
|
#!/bin/bash
|
|
|
|
|
|
|
|
# kernel-cleanup.sh - Remove obsolete packages and config files
|
|
|
|
# {{ ansible_managed }}
|
|
|
|
|
|
|
|
# Determine the active running kernel
|
|
|
|
RUNNING_KERNEL="$( uname -v | awk '{ print $4 }' )"
|
|
|
|
|
2023-09-01 15:42:25 -04:00
|
|
|
# Determine the list of installed kernels (latest first)
|
|
|
|
INSTALLED_KERNEL_PACKAGES=( $( dpkg -l | grep 'linux-image-[0-9]' | awk '{ print $2 }' | sort -Vr ) )
|
|
|
|
NUM_INSTALLED=${{ '{#' }}INSTALLED_KERNEL_PACKAGES[@]}
|
2023-09-01 15:42:25 -04:00
|
|
|
|
|
|
|
if [[ ${NUM_INSTALLED} -le 1 ]]; then
|
|
|
|
echo "A single kernel is installed, aborting cleanly."
|
|
|
|
exit 0
|
|
|
|
fi
|
|
|
|
|
2023-09-01 15:42:25 -04:00
|
|
|
LATEST_KERNEL_PACKAGE="${INSTALLED_KERNEL_PACKAGES[0]}"
|
|
|
|
LATEST_KERNEL="$( dpkg -l | grep "${LATEST_KERNEL_PACKAGE}" | awk '{ print $3 }' )"
|
2023-09-01 15:42:25 -04:00
|
|
|
if [[ ${LATEST_KERNEL} == ${RUNNING_KERNEL} ]]; then
|
|
|
|
force=""
|
2023-09-01 15:42:25 -04:00
|
|
|
else
|
|
|
|
force="--allow-remove-essential"
|
2023-09-01 15:42:25 -04:00
|
|
|
fi
|
|
|
|
|
|
|
|
# Remove the latest kernel from the array
|
|
|
|
NUM_REMOVABLE=$(( ${NUM_INSTALLED} - 1 ))
|
2023-09-01 15:42:25 -04:00
|
|
|
REMOVABLE_KERNEL_PACKAGES=( ${INSTALLED_KERNEL_PACKAGES[@]:1} )
|
2023-09-01 15:42:25 -04:00
|
|
|
|
|
|
|
# Override the "linux-check-removal" script
|
|
|
|
mv /usr/bin/linux-check-removal /usr/bin/linux-check-removal.orig
|
|
|
|
echo -e '#!/bin/sh\necho "Overriding default linux-check-removal script!"\nexit 0' > /usr/bin/linux-check-removal
|
|
|
|
chmod +x /usr/bin/linux-check-removal
|
|
|
|
|
|
|
|
# Remove the packages
|
2023-09-01 15:42:25 -04:00
|
|
|
echo "Removing: ${REMOVABLE_KERNEL_PACKAGES[@]}"
|
|
|
|
apt-get purge --yes ${force} ${REMOVABLE_KERNEL_PACKAGES[@]}
|
2023-09-01 15:42:25 -04:00
|
|
|
|
|
|
|
# Restore the "linux-check-removal" script
|
|
|
|
mv /usr/bin/linux-check-removal.orig /usr/bin/linux-check-removal
|
|
|
|
|
|
|
|
# Make sure there is still a valid kernel installed (just in case something broke)
|
|
|
|
if [[ $( dpkg -l | grep 'linux-image-[0-9]' | wc -l ) -lt 1 ]]; then
|
|
|
|
echo "WARNING: NO KERNEL IS INSTALLED. THROWING ERROR AND ABORTING."
|
|
|
|
exit 1
|
|
|
|
fi
|
2023-09-01 15:42:25 -04:00
|
|
|
|
|
|
|
update-grub
|
|
|
|
|
2023-09-01 15:42:25 -04:00
|
|
|
exit 0
|