#! /bin/sh

# Variables
UPGRADE_TYPE="upgrade"

# Help
HelpMsg () {
  echo "Options (some can be combined) :\n  -u : only download new lists of packages\n  -d : only download new packages, no upgrade (not compatible with \"-u\")\n  -i : use \"dist-upgrade\" instead of \"upgrade\"\n  -s : Silent mode (works only with \"-u\" -or \"-d\" for system safety reasons)\n  -h : Print this help message and exit\nWith no parameters, a typical operation is done (update, upgrade and clean)\n"
}

# getopts (Gestion des options)
while getopts "udsih" MyOption ; do
  case $MyOption in
    u)
      UPDATE_ONLY="1"
      ;;
    d)
      DOWNLOAD_ONLY="-d"
      ;;
    i)
      UPGRADE_TYPE="dist-upgrade"
      ;;
    s)
      SILENT_MODE="-qq"
      ;;
    h)
      HelpMsg ; exit 0
      ;;
    ?)
      HelpMsg ; exit 1
      ;;
  esac
done

# Incompatible options
if [ "$UPDATE_ONLY" = "1" -a "$DOWNLOAD_ONLY" = "-d" ] ; then
  echo "Options \"-u\" and \"-d\" are not compatible."
  exit 1
fi

# Silent mode is for update or download only, not for real upgrades
if [ "$SILENT_MODE" = "-qq" ] ; then
  if [ "$UPDATE_ONLY" != "1" -a "$DOWNLOAD_ONLY" != "-d" ] ; then
    echo "This is too dangerous. Please do it manually."
    exit 1
  fi
fi

# Let's go : update...
sudo apt-get $SILENT_MODE update
test "$UPDATE_ONLY" = "1" && exit 0

# ...upgrade...
sudo apt-get $SILENT_MODE $DOWNLOAD_ONLY $UPGRADE_TYPE ; APT_RC=$?

# ...and clean
if [ "$APT_RC" = "0" ] ; then
  test "$DOWNLOAD_ONLY" = "-d" && exit 0
  echo -n "\nUpgrade successfully completed.\nDeleting packages : "
  sudo apt-get clean && echo "OK" || echo "FAILED"
  echo "Upgrade finished on `cat /etc/hostname`. Exiting."
  exit 0
else
  echo -n "\nUpgrade encountered errors. Press [Enter] to leave.\nNOTE : the downloaded packages WILL NOT be deleted."
  read FOO
  exit 1
fi
