#!/bin/sh
# Threshold package pre-install script (deb "preinst" / rpm "%pre").
#
# Runs before the package files are unpacked. It is safe to run repeatedly and
# never deletes or overwrites anything:
#
#   * Service user: if a HashiCorp Boundary "boundary" user already exists and
#     there is no "threshold" user yet, no new user is created. The postinst
#     script makes the service run as the existing "boundary" user so that its
#     data/log directory ownership keeps working.
#   * Configuration: files from /etc/boundary.d are COPIED to /etc/threshold.d
#     (boundary.hcl -> threshold.hcl, boundary.env -> threshold.env, everything
#     else keeps its name). An existing file in /etc/threshold.d is never
#     replaced, and the originals in /etc/boundary.d are left untouched.
#
# 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"
LEGACY_DIR="$ROOT/etc/boundary.d"
NEW_DIR="$ROOT/etc/threshold.d"

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

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

# Map a top-level legacy file name to its Threshold name.
map_name() {
	case "$1" in
	boundary.hcl) echo "threshold.hcl" ;;
	boundary.env) echo "threshold.env" ;;
	*) echo "$1" ;;
	esac
}

# copy_tree SRC_DIR DST_DIR TOPLEVEL(0/1)
# Copies entries that do not exist yet in DST_DIR; never overwrites.
copy_tree() {
	_src=$1
	_dst=$2
	_top=$3
	for _f in "$_src"/* "$_src"/.[!.]*; do
		if [ ! -e "$_f" ] && [ ! -L "$_f" ]; then
			continue
		fi
		_name=${_f##*/}
		if [ "$_top" = 1 ]; then
			_name=$(map_name "$_name")
		fi
		_target="$_dst/$_name"
		if [ -d "$_f" ] && [ ! -L "$_f" ]; then
			if [ -d "$_target" ]; then
				copy_tree "$_f" "$_target" 0
			elif [ -e "$_target" ] || [ -L "$_target" ]; then
				say "not replacing existing $_target"
			else
				cp -pR "$_f" "$_target"
				say "copied $_f -> $_target"
			fi
		elif [ -e "$_target" ] || [ -L "$_target" ]; then
			# Already present (user's own file, or a previous run): keep it.
			:
		else
			cp -pP "$_f" "$_target"
			say "copied $_f -> $_target"
		fi
	done
}

# --- service user -----------------------------------------------------------
if ! user_exists "$NEW_USER"; then
	if user_exists "$LEGACY_USER"; then
		say "existing '$LEGACY_USER' user found; reusing it instead of creating '$NEW_USER'"
	else
		useradd \
			--system \
			--user-group \
			--shell /bin/false \
			"$NEW_USER"
	fi
fi

# --- configuration migration ------------------------------------------------
if [ -d "$LEGACY_DIR" ]; then
	mkdir -p "$NEW_DIR"
	copy_tree "$LEGACY_DIR" "$NEW_DIR" 1
fi

exit 0
