#!/bin/sh
#
# pfSense-upgrade.wrapper
#
# part of pfSense (https://www.pfsense.org)
# Copyright (c) 2015-2025 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"
lockf_timeout="5"

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

unset boot_stage
while getopts 46b:cCdfi:hp:l:nr:RT:uUy opt; do
	case "${opt}" in
	"b")
		boot_stage="${OPTARG}"
		;;
	"T")
		lockf_timeout="$(printf "%d" "${OPTARG}" 2> /dev/null)"
		;;
	"?")
		"${pfsense_upgrade}" -h
		exit 1
		;;
	*)
		;;
	esac
done

# Force a bigger timeout on the stage 3 upgrade.
# See #17901 and #15638.
[ -n "${boot_stage}" ] && [ "${boot_stage}" = "3" ] && \
    lockf_timeout="300"

if [ -z "${lockf_timeout}" ] || \
    [ "${lockf_timeout}" -lt 2 ] || \
    [ "${lockf_timeout}" -gt 600 ]; then
	echo "ERROR: Invalid timeout value (must be in 2~600 range): ${lockf_timeout}"
	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 "${lockf_timeout}" ${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
