#!/bin/sh
#
# Copyright (c) 2013 M:tier Ltd.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Author: Antoine Jacoutot <antoine@mtier.org>

# TODO
# https://stable.mtier.org/vuxml/53.xml
# check for pkg.conf installpath and/or PKG_PATH
# extend usage() with doc from web

### user defined variables
OPENUP_URL='https://stable.mtier.org/openup'
PKG_CERT_URL='https://stable.mtier.org/mtier.cert'
PKG_CERT_FPRINT='DE:29:0F:7F:B8:0E:36:5A:AF:A9:BF:E0:4E:08:C2:0F:2D:50:16:97'
### end of user defined variables


# DO NOT MODIFY ANYTHING BELOW THIS LINE!!!

usage() {
	echo "usage: ${0##*/} [-SUn]" >&2
	exit 1
}

if [ "$(id -u)" -ne 0 ]; then
	error "need root privileges to run this script"
	usage
fi

# regex taken from fw_update(1)
set -A REL -- $(sysctl -n kern.version | sed 's/^OpenBSD \([0-9]\.[0-9]\)\([^ ]*\).*/\1 \2/;q')
REL_INT="$(echo ${REL[0]} | tr -d '.')"

if [ "${REL[1]}" == -!(stable) ]; then
	error "XXX -current is a no-no"
	exit 1
fi

if [ "${REL_INT}" -lt "${OPENUP_MINREL}" ]; then
	error "XXX release ${REL[0]} is a no-no (non-fatal)"
fi

OPENUP_VERSION=2
OPENUP_MINREL=53
MEESA=$(readlink -f $0)
TMPDIR="${TMPDIR:=/tmp}"
TMPCERT=$(mktemp -p ${TMPDIR} openup-pkg_cert.XXXXXX) || exit 1
TMPUPD=$(mktemp -p ${TMPDIR} openup-update.XXXXXX) || exit 1
TMPSPLITCERT=$(mktemp -p ${TMPDIR} openup-split_cert.XXXXXX) || exit 1

trap "rm -f ${TMPDIR}/openup-*" 1 2 3 13 15

error() {
	echo -n "*** ERROR: $@"
}

print3() {
	echo "===> ${@}${DRYRUN}"
}

print2() {
	echo "==> ${@}"
}

get_cert() {
	local _CMD

	[[ -r /etc/ssl/pkgca.pem ]] && \
		split -p '^-----BEGIN CERTIFICATE-----$' /etc/ssl/pkgca.pem ${TMPSPLITCERT}

	for i in ${TMPSPLITCERT}* ; do
		openssl x509 -noout -in $i -fingerprint 2>/dev/null | \
			grep -q "${PKG_CERT_FPRINT}" && return
	done

	print3 "Downloading certificate"
	_CMD="ftp -Vo ${TMPCERT} ${PKG_CERT_URL}"
	print2 "${_CMD}"
	if [ -z "${DRYRUN}" ]; then
		eval ${_CMD} || exit 1
	fi

	print3 "Installing certificate"
	_CMD="cat ${TMPCERT} >>/etc/ssl/pkgca.pem"
	print2 "${_CMD}"
	if [ -z "${DRYRUN}" ]; then
		eval ${_CMD} || exit 1
	fi
}

update_self() {
	local _CMD _N

	print3 "Checking for openup(8) update"
	_CMD="ftp -Vo ${TMPUPD} ${OPENUP_URL}"
	print2 "${_CMD}"
	if [ -z "${DRYRUN}" ]; then
		eval ${_CMD} || exit 1
	fi

	_N=$(grep -Eo '^OPENUP_VERSION=.*' ${TMPUPD} | awk -F '=' '{ print $2 }')
	[[ -n "${_N}" ]] && \
		if [ "${OPENUP_VERSION}" -lt "${_N}" ]; then
			print3 "Updating openup(8) from version ${OPENUP_VERSION} to version ${_N}"
			_CMD="cat ${TMPUPD} >${MEESA}"
			print2 "${_CMD}"
			eval ${_CMD} || exit 1
			rtn=$?
			print3 "openup(8) updated to version ${_N}, restarting"
			_CMD="${MEESA} -U $@"
			print2 "${_CMD}"
			eval ${_CMD}
			exit $rtn
		fi
}

update_binpatches() {
	local _BP _CMD

	_BP=$(pkg_info -Q binpatch${REL_INT}-$(arch -s) | sed 's/.[^-]*$//' | sort -u | tr '\n' ' ')

	if [ -n "$_BP" ]; then
		print3 "Updating binpatch(es)"
		_CMD="pkg_add ${pkg_opt} ${_BP}"
		print2 "${_CMD}"
		eval ${_CMD}
	fi
}

update_pkg() {
	local _CMD

	print3 "Updating package(s)"
	_CMD="pkg_add -u ${pkg_opt}"
	print2 "${_CMD}"
	eval ${_CMD}
}

update_fw() {
	local _CMD

	print3 "Updating firmware(s)"
	_CMD="fw_update ${fw_opt}"
	print2 "${_CMD}"
	eval ${_CMD}
}

while getopts 'SUn' arg; do
	case ${arg} in
	S)	NOSIG=1; pkg_opt="${pkg_opt} -D nosig" ;;
	U)	NOSELFUPDATE=1 ;;
	n)	DRYRUN=" (dry run)"; pkg_opt="${pkg_opt} -n -D nosig"; fw_opt="-n" ;;
	*)	usage ;;
	esac
done
[ $# = $(($OPTIND-1)) ] || usage

[[ -z $NOSELFUPDATE ]] && update_self
[[ -z $NOSIG ]] && get_cert
update_binpatches
update_pkg
update_fw

rm -f ${TMPDIR}/openup-*
