#!/bin/sh

set -o errexit
set -o nounset

# Copyright (C) 2015 Enno Weichert <enno.weichert@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# HOW TO USE THIS:
# ================
#
# This script is meant to be called by the panel plugin `xfce4-genmon-plugin`
# also called Genmon or Generic Monitor.
# Add the item to the panel and configure it:
# - Use this script as the Command.
# - Use a reasonable time in the Period field.

# -----------------------------------------------------------------------------
# CONFIGURATION:
# ==============
#
# You may want to change this.

urgent_icon="/usr/share/icons/Tango/22x22/status/software-update-urgent.png"
available_icon="/usr/share/icons/Tango/22x22/status/software-update-available.png"
error_icon="/usr/share/icons/Tango/22x22/status/dialog-error.png"
apt_gui_command="/usr/bin/synaptic-pkexec"

# -----------------------------------------------------------------------------

die () { # errcode message
	errcode=$1; shift
	message="$*"
	cat <<- EOT 1>&2
	<img>${error_icon}</img>
	<tool>Error: ${message}</tool>
	EOT
	exit "$errcode"
}

apt_out="$(apt-get --just-print upgrade)" || die 1 "Failed to run apt-get"
apt_upgrades="$(echo "${apt_out}" | egrep --only-matching '^[0-9]+ upgraded' | egrep --only-matching [0-9]+)" || die 1 "Failed to parse for upgrades"
apt_security="$(echo "${apt_out}" | grep "^Inst" | grep --ignore-case securi)" || die 1 "Failed to parse for security upgrades"

if [ "${apt_upgrades}" -gt 0 ]; then
	if [ -n "${apt_security}" ]; then
		cat <<- EOT
		<img>${urgent_icon}</img>
		<tool>${apt_upgrades} software update(s) available including urgent updates</tool>
		EOT
	else
		cat <<- EOT
		<img>${available_icon}</img>
		<tool>${apt_upgrades} software update(s) available</tool>
		EOT
	fi
	cat <<- EOT
	<click>${apt_gui_command}</click>
	EOT
else
	echo
fi
