#!/bin/sh

ver_old="$2"

if [ "$(apk version -t "$ver_old" '6.8.1-r6')" = '<' ]; then
	if [ "$(stat -c "%a" /etc/doas.d)" = "755" ]; then
		chmod 0750 /etc/doas.d
	fi
fi

if [ "$(apk version -t "$ver_old" '6.8.1-r4')" = '<' ]; then
	:  # do nothing, this is prior renaming /etc/doas.conf to /etc/doas.d/doas.conf

# Undo what was done by the previous post-{install,upgrade} script.
elif [ "$(apk version -t "$ver_old" '6.8.2-r5')" = '<' ]; then
	cat >&2 <<-EOF
	*
	* Since 6.8.2-r5, doas reads both /etc/doas.conf and /etc/doas.d/*.conf
	* (if exists), in this order, and /etc/doas.conf is required to exist.
	*
	EOF
	if [ -L /etc/doas.conf ] && [ "$(readlink -f /etc/doas.conf)" = '/etc/doas.d/doas.conf' ]; then
		cat >&2 <<-EOF
		* Removing /etc/doas.conf symlink and moving /etc/doas.d/doas.conf
		* to /etc/doas.conf.
		*
		EOF
		rm /etc/doas.conf  # symlink
		mv /etc/doas.d/doas.conf /etc/doas.conf  # user's config

		# Remove outdated comment added by the previous post-upgrade script.
		# Note: /etc/doas.conf.apk-new has been created by the upgrade,
		#  so it already has correct perms.
		cat /etc/doas.conf \
			| tr '\n' '\f' \
			| sed 's|# This file is actually located at /etc/doas.d/doas.conf, and reflects\f# the system doas configuration.  It may have been migrated from its\f# previous location, /etc/doas.conf, automatically.\f||' \
			| tr '\f' '\n' \
			> /etc/doas.conf.apk-new

	# Note: If /etc/doas.conf existed, the package upgrade has created
	# doas.conf.apk-new.
	elif [ -f /etc/doas.conf ] && [ -f /etc/doas.conf.apk-new ] && [ "$(ls /etc/doas.d/*.conf 2>/dev/null)" ]; then
		bakfile='/etc/doas.conf.bak'
		[ -e "$bakfile" ] && bakfile="$bakfile$(date +%s)"

		cat >&2 <<-EOF
		*! CAUTION: /etc/doas.conf already exists and /etc/doas.d is not empty,
		*! so it's been ignored until now! Renaming it to $bakfile.
		*! It's strongly recommended that you check your configuration!
		*
		EOF
		mv /etc/doas.conf "$bakfile"  # user's config
		mv /etc/doas.conf.apk-new /etc/doas.conf  # new config

	elif [ -f /etc/doas.d/doas.conf ]; then
		cat >&2 <<-EOF
		* Moving /etc/doas.d/doas.conf to /etc/doas.conf.
		*
		EOF
		mv /etc/doas.conf /etc/doas.conf.apk-new  # new config
		mv /etc/doas.d/doas.conf /etc/doas.conf  # user's config
	fi
fi

exit 0
