#!/bin/sh
# Threshold package post-install script (deb "postinst" / rpm "%post").
#
# Completes an in-place upgrade from a HashiCorp Boundary install. Safe to run
# repeatedly; never deletes user configuration or data:
#
#   1. If the legacy "boundary" user exists and there is no "threshold" user,
#      run the service as "boundary" through a systemd drop-in, so existing
#      data/log directory ownership keeps working.
#   2. Provide a "boundary" command: /usr/bin/boundary -> threshold, only if
#      /usr/bin/boundary does not exist.
#   3. If the legacy boundary.service is enabled/active: stop it, carry its
#      enablement over to threshold.service, and start threshold.service if the
#      old service was running (rolling back to boundary.service if that fails).
#   4. Make "systemctl <verb> boundary" address threshold.service by adding a
#      boundary.service alias symlink, unless something already exists there.
#
# THRESHOLD_PKG_ROOT exists only so the logic can be exercised by
# .release/linux/test/test-package-scripts.sh without root; it is empty in
# normal use.

set -eu

ROOT="${THRESHOLD_PKG_ROOT:-}"
NEW_USER="threshold"
LEGACY_USER="boundary"
UNIT="threshold.service"
LEGACY_UNIT="boundary.service"
SYSTEMD_ETC="$ROOT/etc/systemd/system"
DROPIN_DIR="$SYSTEMD_ETC/threshold.service.d"
DROPIN="$DROPIN_DIR/10-legacy-boundary-user.conf"
DROPIN_MARK="# Managed by the Threshold package (legacy boundary user reuse)"

say() {
	echo "threshold postinst: $*" >&2
}

user_exists() {
	id -u "$1" >/dev/null 2>&1
}

have_systemd() {
	command -v systemctl >/dev/null 2>&1 && [ -d "$ROOT/run/systemd/system" ]
}

# Print the Id= systemd resolves a unit name to (follows aliases).
unit_id() {
	systemctl show -p Id "$1" 2>/dev/null | sed -n 's/^Id=//p'
}

unit_load_state() {
	systemctl show -p LoadState "$1" 2>/dev/null | sed -n 's/^LoadState=//p'
}

# Where the packaged threshold.service lives (merged-usr or not).
packaged_unit_path() {
	for _p in "$ROOT/usr/lib/systemd/system/$UNIT" "$ROOT/lib/systemd/system/$UNIT"; do
		if [ -f "$_p" ]; then
			echo "${_p#"$ROOT"}"
			return 0
		fi
	done
	return 1
}

# --- 1. legacy service user -------------------------------------------------
if user_exists "$LEGACY_USER" && ! user_exists "$NEW_USER"; then
	_group=$(id -gn "$LEGACY_USER" 2>/dev/null || echo "$LEGACY_USER")
	_content="$DROPIN_MARK
[Service]
User=$LEGACY_USER
Group=$_group"
	if [ -e "$DROPIN" ] && ! grep -qF "$DROPIN_MARK" "$DROPIN"; then
		say "leaving existing $DROPIN untouched (not managed by this package)"
	else
		mkdir -p "$DROPIN_DIR"
		_tmp="$DROPIN.tmp.$$"
		printf '%s\n' "$_content" >"$_tmp"
		mv -f "$_tmp" "$DROPIN"
		say "service will run as existing user '$LEGACY_USER' ($DROPIN)"
	fi
fi

# --- 2. "boundary" command ----------------------------------------------------
_bin="$ROOT/usr/bin/boundary"
if [ ! -e "$_bin" ] && [ ! -L "$_bin" ]; then
	if [ -e "$ROOT/usr/bin/threshold" ]; then
		ln -s threshold "$_bin"
	fi
elif [ ! -L "$_bin" ]; then
	say "/usr/bin/boundary is still the HashiCorp Boundary binary (old package installed); leaving it"
	say "after removing the old package run: ln -s threshold /usr/bin/boundary"
fi

# --- 3 + 4. legacy systemd service ----------------------------------------------
if have_systemd; then
	_alias="$SYSTEMD_ETC/$LEGACY_UNIT"

	if [ -L "$_alias" ]; then
		# Already aliased (previous run): nothing to migrate.
		:
	elif [ -e "$_alias" ]; then
		say "$_alias is a custom unit; not touching the legacy service."
		say "move it away and re-run the package configuration to migrate."
	else
		_id=$(unit_id "$LEGACY_UNIT")
		_load=$(unit_load_state "$LEGACY_UNIT")
		_legacy_present=0
		_was_enabled=0
		_was_active=0
		if [ "$_id" = "$LEGACY_UNIT" ] && [ "$_load" = "loaded" ]; then
			_legacy_present=1
			if systemctl is-enabled --quiet "$LEGACY_UNIT" 2>/dev/null; then
				_was_enabled=1
			fi
			if systemctl is-active --quiet "$LEGACY_UNIT" 2>/dev/null; then
				_was_active=1
			fi
		fi

		# Only act on upgrades: a legacy unit or legacy config is present.
		if [ "$_legacy_present" = 1 ] || [ -d "$ROOT/etc/boundary.d" ]; then
			if [ "$_was_active" = 1 ]; then
				say "stopping $LEGACY_UNIT"
				systemctl stop "$LEGACY_UNIT" || say "could not stop $LEGACY_UNIT"
			fi
			if [ "$_was_enabled" = 1 ]; then
				systemctl disable "$LEGACY_UNIT" >/dev/null 2>&1 || say "could not disable $LEGACY_UNIT"
			fi

			# Alias symlink so `systemctl restart boundary` reaches threshold.service.
			if _unit_path=$(packaged_unit_path); then
				mkdir -p "$SYSTEMD_ETC"
				ln -s "$_unit_path" "$_alias"
			fi
			systemctl daemon-reload || true

			if [ "$_was_enabled" = 1 ]; then
				systemctl enable "$UNIT" >/dev/null 2>&1 || say "could not enable $UNIT"
			fi
			if [ "$_was_active" = 1 ]; then
				if systemctl start "$UNIT"; then
					say "$LEGACY_UNIT migrated to $UNIT (config: /etc/threshold.d)"
				else
					say "FAILED to start $UNIT; rolling back to $LEGACY_UNIT"
					systemctl disable "$UNIT" >/dev/null 2>&1 || true
					rm -f "$_alias"
					systemctl daemon-reload || true
					if [ "$_was_enabled" = 1 ]; then
						systemctl enable "$LEGACY_UNIT" >/dev/null 2>&1 || true
					fi
					systemctl start "$LEGACY_UNIT" || say "could not restart $LEGACY_UNIT"
				fi
			elif [ "$_was_enabled" = 1 ]; then
				say "$LEGACY_UNIT enablement carried over to $UNIT (not started: it was stopped)"
			fi
		fi
	fi
	# Pick up a new/changed user drop-in even when no migration was needed.
	systemctl daemon-reload || true
fi

exit 0
