#!/bin/bash
APTGET=$(which apt-get)

usage() {
cat 1>&2 <<EOF
usage: $0

    removes any old kernels (and headers) still installed on your system
    after that, it suggests to push the new changes in /etc

    flags
        -p   purge instead of a simple remove
        -r   auto-remove dependencies
        -y   automatically answer "yes" to all questions
        -n   dry run (don't actually do anything)
        -h   print this help

EOF
}

aptflags=""

OPTIND=1 # Reset is necessary if getopts was used previously in the script.  It is a good idea to make this local in a function.
while getopts "npryh" opt; do
  case "$opt" in
    h)
      usage
      exit 0
      ;;
    p)  aptflags="${aptflags} --purge"
      ;;
    n)  aptflags="${aptflags} --dry-run"
      ;;
    r)  aptflags="${aptflags} --autoremove"
      ;;
    y)  aptflags="${aptflags} --yes"
      ;;
    '?')
      usage
      exit 1
      ;;
    esac
done

_getpkgversion() {
    dpkg -s "$1" | egrep "^Version:" | sed -e 's|^Version:||' -e 's|[[:space:]]||g'
}
_getkernelpkgs() {
    local current=$1
    local curversion=$(_getpkgversion "${current}")

    for pkg in $(dpkg-query -S /lib/modules /usr/lib/modules 2>/dev/null | sed -e 's|:.*||' -e 's|, | |g'); do
        if [ "x${pkg}" = "x${current}" ]; then continue; fi
        if [ "x${pkg}" = "x${p#linux-}" ]; then continue; fi
        if dpkg --compare-versions "${curversion}" gt $(_getpkgversion "${pkg}"); then
            echo $pkg
        else
            echo "skipping newer package: $pkg" 1>&2
        fi
    done
}

do_removeoldkernels() {
    local curmoduledir
    curmoduledir="lib/modules/$(uname -r)/kernel/"
    currentpkg=$(dpkg -S "/${curmoduledir}" "/usr/${curmoduledir}" 2>/dev/null | sed -e 's|:.*||')
    allpkgs=$(_getkernelpkgs "${currentpkg}")
    if [ "x${allpkgs}" != x ]; then
        "${APTGET}" remove ${aptflags} $allpkgs
    else
        false
    fi
}

echo "Current kernel: $(uname -r)"
do_removeoldkernels && virtshaus-pushetc
