#!/bin/sh

kmods="$( pkg -vv | grep FreeBSD-kmods )"
if test "${kmods}" != ""
then
	pkg upgrade -r FreeBSD-kmods
fi
kmods="$( pkg -vv | grep FreeBSD-ports-kmods )"
if test "${kmods}" != ""
then
	pkg upgrade -r FreeBSD-ports-kmods
fi
pkg upgrade
pkg autoremove
pkg clean -qay
pkg version -qo -Rl '?'
pkg annotate -a -S deprecated
pkg annotate -a -S expiration_date
pkg audit

jail_update() {
	jail="${1}"
	name="${jail##*/}"
	printf "\n%s:\n" "${name}"
	jexec "${name}" pkg upgrade
	jexec "${name}" pkg autoremove
	jexec "${name}" pkg clean -qay
	jexec "${name}" pkg version -qo -Rl '?'
	jexec "${name}" pkg annotate -a -S deprecated
	jexec "${name}" pkg annotate -a -S expiration_date
	jexec "${name}" pkg audit
}

chroot_update() {
	jail="${1}"
	name="${jail##*/}"
	printf "\n%s:\n" "${name}"
	chroot "${jail}" pkg upgrade
	chroot "${jail}" pkg autoremove
	chroot "${jail}" pkg clean -qay
	chroot "${jail}" pkg version -qo -Rl '?'
	chroot "${jail}" pkg annotate -a -S deprecated
	chroot "${jail}" pkg annotate -a -S expiration_date
	chroot "${jail}" pkg audit
}

find_jail() {
	name=`jls -n | fgrep " path=${jail} " | tr ' ' '\n' | grep "^name="`
	name="${name#name=}"
	case "${name}" in
	'')
		chroot_update "${jail}"
		;;
	*)
		jail_update "${name}"
		;;
	esac
}

list=""
case "${1}" in
'')
	ARCH=`make -V MACHINE_ARCH`
	HOST=`hostname -s`"-${ARCH}"
	list=""
	for listfile in \
		"/usr/local/etc/jails.pkg.txt" \
		"/usr/local/etc/jails.txt" \
		"/usr/src/jails-${HOST}.pkg.txt" \
		"/usr/src/jails-${HOST}.txt"
	do
		if test ! -f "${listfile}"
		then
			continue
		fi
		list=`grep -v "^#" "${listfile}"`
		break
	done
	;;
*)
	list="${@}"
	;;
esac

for jail in ${list}
do
	if test ! -f "${jail}/var/db/pkg/local.sqlite"
	then
		continue
	fi
	find_jail "${jail}"
done

# eof
