#! /bin/sh

echo "\nRunning \"sudo apt-get autoremove\" :"
sudo apt-get autoremove --purge

echo -n "\nUnused library packages: "
PKGS_TO_REMOVE=`deborphan | sed -e "s/:.*$//" | xargs`
if [ -z "$PKGS_TO_REMOVE" ] ; then
  echo "none."
else
  echo "\n\n$PKGS_TO_REMOVE"
  echo -n "\nRemove ? (y/n) ? " ; read ANSWER
  if [ "$ANSWER" = "y" -o "$ANSWER" = "Y" ] ; then
    while [ "`deborphan`" ] ; do
      sudo apt-get remove --purge --auto-remove `deborphan`
    done
  fi
fi

for PKG_TYPE in common data debug dev doc dummy kernel interpreters mono perl pike python ruby section ; do
  echo -n "\nUnused $PKG_TYPE packages: "
  PKGS_TO_REMOVE=`deborphan --priority standard --guess-only --guess-$PKG_TYPE | sed -e "s/:.*$//" | xargs`
  if [ -z "$PKGS_TO_REMOVE" ] ; then
    echo "none."
  else
    echo "\n\n$PKGS_TO_REMOVE"
    echo -n "\nRemove ? (y/n) ? " ; read ANSWER
    if [ "$ANSWER" = "y" -o "$ANSWER" = "Y" ] ; then
      while [ "`deborphan --priority standard --guess-only --guess-$PKG_TYPE`" ] ; do
        sudo apt-get remove --purge --auto-remove `deborphan --priority standard --guess-only --guess-$PKG_TYPE`
      done
    fi
  fi
done

echo -n "\nResidual config files: "
PKGS_TO_REMOVE=`deborphan --find-config`
if [ -z "$PKGS_TO_REMOVE" ] ; then
  echo "none."
else
  echo "\n\n$PKGS_TO_REMOVE"
  echo -n "\nRemove ? (y/n) ? " ; read ANSWER
  if [ "$ANSWER" = "y" -o "$ANSWER" = "Y" ] ; then
    sudo dpkg --purge `deborphan --find-config`
  fi
fi
