#!/bin/bash

function log() {
	echo "`date` $1"
}
function log_indented() {
	log "===>> $1"
}

function margin() {
	log ""
}

function margin_large() {
	margin
	margin
}

# See https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash with just one change replacing - with .
vercomp () {
    if [[ $1 == $2 ]]
    then
        return 0
    fi
    #local i ver3=($1) ver4=($2)
    ver3=$(echo $1 | sed "s/[-]/\./") ver4=$(echo $2 | sed "s/[-]/\./")
    local IFS=.
    local i ver1=($ver3) ver2=($ver4)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++))
    do
        if [[ -z ${ver2[i]} ]]
        then
            # fill empty fields in ver2 with zeros
            ver2[i]=0
        fi
        if ((10#${ver1[i]} > 10#${ver2[i]}))
        then
            return 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]}))
        then
            return 2
        fi
    done
    return 0
}

testvercomp () {
    vercomp $1 $2
    case $? in
        0) op='=';;
        1) op='>';;
        2) op='<';;
    esac
    if [[ $op != $3 ]]
    then
        echo "Fail: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'"
    else
        echo "Pass: '$1 $op $2'"
    fi
}

log "Starting NRC/NCN upgrade cleanup session to auto remove unused packages."
margin_large

log_indented "Removing old kernel packages ..."
margin

VERSIONS=$(ls -ltr /boot/vmlinuz-* |awk '{print $NF}' | sed -e "s/[^\-]*-//" -e "s/-[^\-]*$//")
CURRENT_KERNEL_VERSION=$(uname -r | sed -e "s/-[^\-]*$//")
VERSION=`echo $CURRENT_KERNEL_VERSION | cut -d '.' -f 1,2`
log_indented "Current kernel version is: $CURRENT_KERNEL_VERSION"
margin
PURGE=""

for v in $VERSIONS; do
        if [[ "$v" != "$CURRENT_KERNEL_VERSION" ]]; then
                for k in linux-image linux-headers linux-kbuild; do
			MATCH=$(testvercomp $CURRENT_KERNEL_VERSION $v '>')
                	if [[ $MATCH == *"Pass"* ]]; then
                        	log_indented "Found kernel older than current booted kernel"
                                margin_large
                        	if [[ "$k" == "linux-image" ]]; then
                                	dpkg -s $k-$v-amd64 &> /dev/null
                                	if [ $? -eq 0 ]; then PURGE="$PURGE $k-$v-amd64"; fi
                       		elif [[ "$k" == "linux-kbuild" ]]; then
                                	if [[ "$VERSION" != "`echo $v | cut -d '.' -f 1,2`" ]]; then
                                        	dpkg -s $k-`echo $v | cut -d '.' -f 1,2` &> /dev/null
                                        	if [ $? -eq 0 ]; then PURGE="$PURGE $k-`echo $v | cut -d '.' -f 1,2`"; fi
                                	fi
                        	else
                                	for f in amd64 common; do
                                        	dpkg -s $PURGE $k-$v-$f &> /dev/null
                                        	if [ $? -eq 0 ]; then PURGE="$PURGE $k-$v-$f"; fi
                        		done
                                fi
                        elif [[ $MATCH == *"Fail"* ]]; then
                        	log_indented "Found kernel newer than current booted kernel"
                                margin_large
			fi
                done
        fi
done

if [ -z "$PURGE" ]; then
        log_indented "No kernels are eligible for removal"
		margin_large
fi

log_indented "About to remove the following kernel packages:"
margin
log_indented "$PURGE"
margin_large
margin_large

sudo apt-get --yes remove --purge $PURGE

log_indented "Removing packages in purged state."
margin
sudo apt-get remove -y --purge $(dpkg -l | grep "^rc" | awk '{print $2}')
margin_large
margin_large

log_indented "Removing packages from the cache..."
margin
sudo apt-get clean
margin_large
log_indented "Successfully cleaned up the packages from the cache."
margin_large
margin_large

log_indented "About to start removing unused packages ..."
margin
sudo apt-get --yes --allow-downgrades --allow-remove-essential --allow-change-held-packages --allow-unauthenticated autoremove 2>&1
if [ "$?" != "0" ]; then
  margin
	log_indented "Warning. Could not auto-remove unused packages."
	exit 0
fi
margin_large
log_indented "Successfully cleaned up unused packages."
exit 0
