#!/bin/sh

# KEYWORD: firstboot
# PROVIDE: firstboot_pkg_upgrade
# REQUIRE: syslogd NETWORKING
# BEFORE: LOGIN

# Add the following lines to /etc/rc.conf.local or /etc/rc.conf (in the
# disk image, since this only runs on the first boot) to enable this:
#
# firstboot_pkg_upgrade_enable="YES"
#
# By default this upgrades all packages, to limit this to a specific repo,
# write it in firstboot_pkg_upgrade_repos, e.g.,
#
# firstboot_pkg_upgrade_repos="FreeBSD-Base FreeBSD-Ports"
#
# By default this script will only run on *-BETA*, *-RC*, and *-RELEASE*
# systems, since those are the only ones for which updates are provided
# by the FreeBSD project; to run pkg upgrade anyway (e.g., on a custom
# release for which you are providing your own pkg repo), set:
#
# firstboot_pkg_upgrade_nonstandard="YES"

. /etc/rc.subr

: ${firstboot_pkg_upgrade_enable:="NO"}
: ${firstboot_pkg_upgrade_nonstandard:="NO"}

name="firstboot_pkg_upgrade"
rcvar=firstboot_pkg_upgrade_enable
start_cmd="firstboot_pkg_upgrade_run | logger -s -t pkg"
stop_cmd=":"

firstboot_pkg_upgrade_run()
{

	if ! checkyesno firstboot_pkg_upgrade_nonstandard; then
		case "`uname -r`" in
		*-BETA* | *-RC* | *-RELEASE*)
			;;
		*)
			echo "Firstboot pkg upgrade disabled on `uname -r`"
			return 0
		;;
		esac
	fi
	
	state_orig=`stat -f %z /var/db/pkg/local.sqlite`
	
	pkg -N > /dev/null 2>&1 || pkg bootstrap -y
	
	repo_args=""

	for repo in ${firstboot_pkg_upgrade_repos}; do
		repo_args="${repo_args} -r ${repo}"
	done

	env AUTOCLEAN=ON pkg upgrade ${repo_args} -y

	state_new=`stat -f %z /var/db/pkg/local.sqlite`

        if [ $state_orig != $state_new ]; then
                echo "Requesting reboot after installing updates."
                touch ${firstboot_sentinel}-reboot
        fi
}

load_rc_config $name
run_rc_command "$1"

