#!/bin/sh
#
# pfSense-upgrade.wrapper
#
# part of pfSense (https://www.pfsense.org)
# Copyright (c) 2015-2022 Rubicon Communications, LLC (Netgate)
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

pfsense_upgrade=$(realpath -q $(dirname $0)/../libexec/$(basename $0))
lockfile="/tmp/$(basename $0).lock"

if [ ! -f ${pfsense_upgrade} ]; then
	echo "ERROR: Unable to find ${pfsense_upgrade}"
	exit 1
fi

if [ "$(id -u)" -ne "0" ]; then
	echo "ERROR: It must run as root"
	exit 1
fi

# lockf return codes, from sysexits(3)
EX_TEMPFAIL=75	# The specified lock file was already locked by another process.
EX_CANTCREAT=73	# The lockf utility was unable to create the lock file, e.g.,
		# because of insufficient access privileges.
EX_OSERR=71	# A system call (e.g., fork(2)) failed unexpectedly.
EX_SOFTWARE=70	# The command did not exit normally, but may have been signaled
		# or stopped.

# Special return code to detect when pfSense-upgrade was upgraded and must
# be called again to make sure latest version is running
EX_UPGRADE=99

while true; do
	unset run_again
	/usr/bin/lockf -s -t 5 ${lockfile} ${pfsense_upgrade} "$@"
	rc=$?

	unset error
	case "$rc" in
		${EX_TEMPFAIL})
			echo "Another instance is already running... Aborting!"
			exit $EX_TEMPFAIL
			;;
		${EX_CANTCREAT})
			echo "ERROR: Unable to create lockfile ${lockfile}"
			exit $EX_CANTCREAT
			;;
		${EX_OSERR})
			echo "ERROR: An unexpected OS error happened"
			error=$EX_OSERR
			;;
		${EX_SOFTWARE})
			echo "ERROR: An unexpected error happened"
			error=$EX_SOFTWARE
			;;
		${EX_UPGRADE})
			run_again=1
			;;
	esac

	[ -f "${lockfile}" ] \
		&& rm -f ${lockfile}

	[ -n "${error}" ] \
		&& exit $error

	[ -n "${run_again}" ] \
		&& continue

	exit $rc
done
