#!/bin/sh
# tools/post-install.sh — wire system PATH after `make install`, and
# reverse it on `make uninstall`. Idempotent on both sides.
#
# Usage: tools/post-install.sh <install|uninstall> <prefix>
#
# Behavior by host OS (uname -s):
#
#   SunOS (illumos / Solaris) with prefix not in /usr or /usr/local:
#     Add or remove $prefix/bin to/from the PATH= line of /etc/default/login
#     (override with LOGIN_DEFAULTS=...). illumos man(1) derives the manpath
#     from PATH by replacing trailing /bin with /share/man, so wiring PATH
#     is enough for `man party` to work without -M.
#
#   Linux / *BSD / macOS with prefix in {/usr, /usr/local}:
#     Already on default PATH and MANPATH. No-op.
#
#   Anything else (custom PREFIX on Linux/BSD/macOS, or unknown OS):
#     Print the export lines the user needs to add to a shell rc.
#     Do not mutate any system file.
#
# DESTDIR-aware: the Makefile skips this script entirely when DESTDIR is set
# (package staging context — mutating /etc on the build host is wrong).

set -eu

usage() {
	echo "usage: $0 <install|uninstall> <prefix>" >&2
	exit 2
}

[ $# -eq 2 ] || usage
action=$1
prefix=$2
case "$action" in install|uninstall) ;; *) usage ;; esac
[ -n "$prefix" ] || usage

bindir="$prefix/bin"
mandir="$prefix/share/man"
LOGIN_DEFAULTS=${LOGIN_DEFAULTS:-/etc/default/login}
uname_s=$(uname -s)

# Print install- or uninstall-side instructions for setting/clearing PATH and
# MANPATH in a shell rc. Used when we don't (or won't) edit any system file.
print_manual_instructions() {
	verb=$1 bd=$2 md=$3 osname=$4
	if [ "$osname" = "Linux" ] || [ "$osname" = "FreeBSD" ] || [ "$osname" = "NetBSD" ] \
	  || [ "$osname" = "OpenBSD" ] || [ "$osname" = "DragonFly" ] || [ "$osname" = "Darwin" ]; then
		header="PREFIX is non-standard on $osname; not modifying system files."
	else
		header="Unrecognized OS '$osname'; not modifying system files."
	fi
	if [ "$verb" = "install" ]; then
		cat <<EOF
$header
For 'party' and 'man party' to work in fresh shells, add to your shell rc:

    export PATH="$bd:\$PATH"
    export MANPATH="$md:\$MANPATH"
EOF
	else
		cat <<EOF
$header
If you previously added these to your shell rc, remove them:

    export PATH="$bd:\$PATH"
    export MANPATH="$md:\$MANPATH"
EOF
	fi
}

# Idempotently add ($verb=install) or remove ($verb=uninstall) $needle as a
# component of the PATH= line in $file. Returns 0 in all expected cases —
# only awk/IO failures bubble up as nonzero. Prints what it did.
edit_path_line() {
	verb=$1 file=$2 needle=$3

	if [ ! -f "$file" ]; then
		echo "$file does not exist; skipping PATH wiring." >&2
		return 0
	fi
	if [ ! -w "$file" ]; then
		echo "$file is not writable (run as root); skipping PATH wiring." >&2
		return 0
	fi

	tmpf="$file.party.tmp.$$"
	# awk exits 0 if it modified the file, 1 if no change was needed.
	if awk -v verb="$verb" -v needle="$needle" '
		BEGIN { changed = 0; path_seen = 0 }
		/^PATH=/ && !path_seen {
			path_seen = 1
			val = substr($0, 6)
			n = split(val, parts, ":")
			present = 0
			for (i = 1; i <= n; i++) if (parts[i] == needle) present = 1

			if (verb == "install") {
				if (present) { print; next }
				if (val == "") print "PATH=" needle
				else           print $0 ":" needle
				changed = 1
				next
			}
			if (verb == "uninstall") {
				if (!present) { print; next }
				out = ""
				for (i = 1; i <= n; i++) {
					if (parts[i] == needle) continue
					out = (out == "" ? parts[i] : out ":" parts[i])
				}
				print "PATH=" out
				changed = 1
				next
			}
		}
		{ print }
		END { exit changed ? 0 : 1 }
	' "$file" > "$tmpf"; then
		ts=$(date +%Y%m%d%H%M%S)
		cp -p "$file" "$file.before-party.$ts"
		mv "$tmpf" "$file"
		case "$verb" in
			install)   echo "Added $needle to PATH in $file (backup: $file.before-party.$ts)" ;;
			uninstall) echo "Removed $needle from PATH in $file (backup: $file.before-party.$ts)" ;;
		esac
	else
		rm -f "$tmpf"
		case "$verb" in
			install)   echo "$needle already in PATH in $file; nothing to do." ;;
			uninstall) echo "$needle not in PATH in $file; nothing to do." ;;
		esac
	fi
	return 0
}

case "$uname_s" in
	SunOS)
		case "$prefix" in
			/usr|/usr/local)
				echo "$prefix is on the default illumos PATH; no system wiring needed."
				;;
			*)
				edit_path_line "$action" "$LOGIN_DEFAULTS" "$bindir"
				;;
		esac
		;;
	Linux|FreeBSD|NetBSD|OpenBSD|DragonFly|Darwin)
		case "$prefix" in
			/usr|/usr/local)
				: # already on PATH and MANPATH on these platforms
				;;
			*)
				print_manual_instructions "$action" "$bindir" "$mandir" "$uname_s"
				;;
		esac
		;;
	*)
		print_manual_instructions "$action" "$bindir" "$mandir" "$uname_s"
		;;
esac
