#!/bin/sh
#
# Upgrade packages as root via sudo. Callers may be granted password-less
# sudo for THIS wrapper only (see etc/sudoers.d/install), so every argument
# is checked before it reaches apt: a bare package specifier is allowed;
# apt options ("-o Dir::...", "--"), paths ("/x", "./crafted.deb") and any
# shell metacharacter ("|", "&", ";", ...) are refused -- otherwise a
# caller could escalate to full root (swap dpkg, run maintainer scripts,
# smuggle commands, ...).

if [ "$(id -u)" != 0 ]; then
	exec sudo "$0" "$@"
fi

U=
if [ "$#" -gt 0 ] && [ "$1" = "-U" ]; then
	shift
	U=y
fi

# Accept only name[:arch][=version]-style specifiers, optionally ending in
# "*" for globbing. Reject anything else outright.
ok_arg()
{
	case "$1" in
		''|-*|/*|./*|*/*)				return 1 ;;
		*[!a-zA-Z0-9_.+:=*~-]*)			return 1 ;;
		[a-zA-Z0-9]*)					return 0 ;;
		*)								return 1 ;;
	esac
}

for a in "$@"; do
	if ! ok_arg "$a"; then
		printf '%s: refusing suspicious argument: %s\n' "${0##*/}" "$a" >&2
		exit 2
	fi
done

test -z "$U" || eatmydata apt update -qq
exec eatmydata apt dist-upgrade "$@"
