#!/bin/sh
#
# Spk-rm - Remove SliTaz packages. Read the README before adding or
# modifying any code in spk!
#
# Copyright (C) SliTaz GNU/Linux - BSD License
# Author: See AUTHORS files
#
. /usr/lib/slitaz/libspk.sh

#
# Functions
#

# Help and usage
usage() {
	name=$(basename $0)
	cat << EOT

$(boldify $(gettext "Usage:")) $name [packages|--options]

$(gettext "Remove installed packages and their dependencies")

$(boldify $(gettext "Options:"))
  --auto         $(gettext "Remove without asking for confirmation")
  --force        $(gettext "Allow removing an essential package (dangerous)")
  --nodeps       $(gettext "Remove only the named packages, keep their dependents")
  --autoremove   $(gettext "Remove auto-installed packages no longer needed")
  --root=        $(gettext "Set the root file system path")
  --verbose   $(gettext "Be more verbose when removing files")
  --dry-run   $(gettext "Resolve the plan but do not modify the system")
  --explain   $(gettext "Print the plan as a list of shell commands (implies --dry-run)")
  --trame     $(gettext "JSON object on stdout (implies --dry-run)")
  --raw       $(gettext "Stream removal milestones as flat TSV (for the TUI)")

$(boldify $(gettext "Examples:"))
  $name package1 package2 packagesN
  $name package1 --auto --verbose

EOT
	exit 0
}

# Core packages whose removal bricks the system (no shell, no libc, no base
# files). spk-rm refuses to touch these — directly or dragged in as a reverse
# dep — unless --force is given. Keep this list short and truly critical.
ESSENTIAL="busybox glibc-base slitaz-base-files"
is_essential() {
	case " $ESSENTIAL " in *" $1 "*) return 0 ;; esac
	return 1
}

# Full transitive reverse-dependency closure of $1 — every installed
# package that (directly or indirectly) depends on it and would break if
# it went away. De-duplicated, $1 excluded. Builds the reverse-dep index
# once (O(n), libspk) then walks it, instead of rescanning all receipts
# at every step. $2: an index already built (see rdeps_index), for the
# dry-run, which asks for several names and changes nothing in between.
rdeps_all() {
	local idx="$2"
	[ -n "$idx" ] || idx=$(rdeps_index)
	# Reversed BFS = deepest dependents first: in a chain A→B→target,
	# A must go before B, or B disappears while A's remove hooks still
	# need it. (BFS order alone removed B first.)
	rdeps_closure "$idx" "$1" | tr ' ' '\n' | sed -n '1!G;h;$p' | tr '\n' ' '
	echo
	[ -n "$2" ] || rm -f "$idx"
}

# --nodeps: the installed packages left needing $1 once it is gone, from
# the index $2. Direct dependents only (sole provider, as rdeps_closure):
# theirs is the missing dependency, deeper ones still have theirs. Names
# this call removes too are left out: they will not be left broken.
nodeps_left() {
	local d out=""
	for d in $(awk -v p="$1" '$1==p && $3<=1 {print $2}' "$2"); do
		case " $out $rm_names " in *" $d "*) continue ;; esac
		is_package_installed "$d" && out="$out $d"
	done
	echo $out
}

# Build the reverse-dep index into a new temp file, echo its name.
rdeps_index() {
	# mktemp is the safe path; the fallback rm -f's first so a pre-planted
	# symlink at the predictable name can't redirect the later write.
	local idx=$(mktemp 2>/dev/null)
	[ -n "$idx" ] || { idx="/tmp/spk-rdeps.$$"; rm -f "$idx"; }
	build_rdeps_index "$idx"
	echo "$idx"
}

# Sum the on-disk size (bytes) of the regular files a package owns, read
# from its files.list. Symlinks/dirs skipped. Missing list -> 0. This is
# the real space freed by removing the package.
pkg_disk_bytes() {
	local fl="$installed/$1/files.list"
	[ -f "$fl" ] || { echo 0; return; }
	# One stat for the lot (it never follows symlinks), not one per file.
	awk -v r="${root%/}" '$0 != "" { print r $0 }' "$fl" | tr '\n' '\0' | \
		xargs -0 -r stat -c '%F|%s' 2>/dev/null | \
		awk -F'|' '$1 ~ /^regular/ { t += $2 } END { printf "%.0f\n", t }'
}

# Format a byte count as a 1024-based human-readable size.
human_size() {
	echo "$1" | awk '{ t=$1;
		if(t>=1073741824) printf "%.1fG\n", t/1073741824;
		else if(t>=1048576) printf "%.1fM\n", t/1048576;
		else if(t>=1024) printf "%.1fK\n", t/1024;
		else printf "%dB\n", t; }'
}

# Orphans = auto-installed packages (.auto marker, set by spk-add --asdep)
# that nothing still-needed depends on. A package is removable when every
# package depending on it is itself in the removal set; iterate to a
# fixpoint over the reverse-dep index. Explicit packages are never reaped.
# Echoes the orphan list in dependents-first removal order.
autoremove_set() {
	local idx=$(mktemp 2>/dev/null)
	[ -n "$idx" ] || { idx="/tmp/spk-auto.$$"; rm -f "$idx"; }
	build_rdeps_index "$idx"
	local set="" changed=1 p d keep
	while [ "$changed" ]; do
		changed=
		for p in $(ls $installed 2>/dev/null); do
			[ -f "$installed/$p/.auto" ] || continue
			# Essential packages are never reaped, even auto-installed:
			# an orphaned busybox would still brick the system.
			is_essential "$p" && continue
			case " $set " in *" $p "*) continue ;; esac
			# Keep $p if any of its dependents is NOT being removed.
			keep=
			for d in $(awk -v x="$p" '$1==x{print $2}' "$idx"); do
				case " $set " in *" $d "*) ;; *) keep=yes; break ;; esac
			done
			[ "$keep" ] && continue
			set="$set $p"; changed=1
		done
	done
	rm -f "$idx"
	echo $set
}

# Remove exactly ONE installed package: hooks, files, receipt, DB line.
# No reverse-dep handling, no confirm, no cascade — the caller decides
# the full set and the order. Uses $pkg.
remove() {
	unset_receipt
	source_receipt $installed/$pkg/receipt
	# Never trust PACKAGE from the receipt for the destructive paths below:
	# a truncated/empty receipt (disk-full crash) leaves PACKAGE unset, and
	# `rm -rf $installed/$PACKAGE` would then expand to `rm -rf $installed/`
	# — the entire package DB. A PACKAGE that disagrees with the directory
	# name ($pkg) would wipe a *different* package. Pin every path to $pkg,
	# the directory we were actually asked to remove.
	if [ -z "$PACKAGE" ] || [ "$PACKAGE" != "$pkg" ]; then
		colorize 33 "$(gettext 'Corrupt receipt, using directory name:') $pkg"
		PACKAGE="$pkg"
	fi
	boldify $(gettext "Removing") $pkg
	separator
	[ "$verbose" ] && echo "DB: $installed"

	# Handle pre_remove
	if grep -q ^pre_remove $installed/$PACKAGE/receipt; then
		pre_remove $root || {
			gettext "WARNING: pre_remove failed:"
			colorize 31 " $PACKAGE"; newline; }
	fi

	# Remove all files
	fileslist=$installed/$PACKAGE/files.list
	# No files.list = nothing can be removed from disk: unregistering
	# anyway would orphan every file forever. Refuse and keep the DB entry.
	if [ ! -f "$fileslist" ]; then
		gettext "ERROR: missing files.list, reinstall with --forced first:"
		colorize 31 " $PACKAGE"; newline
		return 1
	fi
	gettext "Installed files:"
	echo -n " $(wc -l $fileslist | cut -d " " -f 1)"
	[ "$verbose" ] && newline
	# Shared-file guard: never delete a file still owned by ANOTHER
	# installed package — doing so silently breaks the package that stays
	# (this is how a careless rm wiped glibc-base's loader and the host
	# /dev nodes shared via devtmpfs). Dependents removed earlier in the
	# same run already had their receipt/files.list deleted, so they don't
	# count here. Mirrors spk-add's modifier check. One awk over every
	# other files.list, whole-line exact match (no regex: a backslash or
	# metachar in a path must not hide or invent a co-owner); a grep of
	# all lists per file took 20 s to remove perl.
	local keep=$(mktemp) gone=$(mktemp) fl
	set --
	for fl in $installed/*/files.list; do
		[ "$fl" = "$fileslist" ] || set -- "$@" "$fl"
	done
	# FILENAME, not NR == FNR: with an empty first file NR == FNR would
	# stay true on the next one (an empty keep list kept everything).
	awk 'FILENAME == ARGV[1] { if ($0 != "") mine[$0]; next }
		($0 in mine) { print; delete mine[$0] }' "$fileslist" "$@" \
		/dev/null > "$keep"
	awk 'FILENAME == ARGV[1] { kept[$0]; next } $0 != "" && !($0 in kept)' \
		"$keep" "$fileslist" > "$gone"
	if [ "$verbose" ]; then
		while IFS= read -r file; do
			gettext "Kept (shared):"; echo " ${root}${file}"
		done < "$keep"
		while IFS= read -r file; do
			gettext "Removing:"; echo " ${root}${file}"
		done < "$gone"
	fi
	# Each path is taken literally (never globbed): see remove_files.
	remove_files "$gone"
	rm -f "$keep" "$gone"
	status

	# Handle post_remove
	if grep -q ^post_remove $installed/$PACKAGE/receipt; then
		post_remove $root || {
			gettext "WARNING: post_remove failed:"
			colorize 31 " $PACKAGE"; newline; }
	fi

	# Kernel modules: modules.dep and friends are made by depmod, so no
	# files.list owns them. Another package still ships files for this
	# kernel: reindex, its modules.dep must not list removed ones. None
	# left: drop the indexes, or /lib/modules/<version> stays forever.
	for kver in $(awk -F/ '$2 == "lib" && $3 == "modules" && $4 != "" {
		print $4 }' $fileslist | sort -u); do
		kdir="$root/lib/modules/$kver"
		[ -d "$kdir" ] || continue
		# Ownership, not a kernel/ dir: a kernel with everything built in
		# ships only modules.builtin/order, which must survive.
		# busybox grep -v exits 1 as soon as one line matches, even if
		# others are printed: test the output, not the status.
		if grep -lsF "/lib/modules/$kver/" $installed/*/files.list |
			grep -v "/$PACKAGE/files.list" | grep -q .; then
			[ -f $root/sbin/depmod ] && chroot "$root/" /sbin/depmod -a $kver
		else
			rm -f "$kdir"/modules.*
			rmdir "$kdir" 2>/dev/null
		fi
	done

	# Icon caches of the themes it touched: drop its icons from them
	if [ -f $root/usr/bin/gtk-update-icon-cache ]; then
		for theme in $(awk -F/ '$2 == "usr" && $3 == "share" &&
			$4 == "icons" && NF > 5 { print $5 }' $fileslist | sort -u); do
			[ -f "$root/usr/share/icons/$theme/icon-theme.cache" ] &&
			[ -f "$root/usr/share/icons/$theme/index.theme" ] || continue
			chroot "$root/" /usr/bin/gtk-update-icon-cache -q -f \
				/usr/share/icons/$theme
		done
	fi

	# Remove package receipt.
	gettext "Removing package receipt..."
	rm -rf $installed/$PACKAGE
	# Drop the installed.$SUM line. The old sed matched
	# "$PACKAGE-$VERSION.tazpkg" literally, missing the real arch-suffixed
	# filename (bc-1.08.2-x86_64.tazpkg) and so leaving a stale md5 entry
	# on every removal — the very orphans spk-doctor now reports. Match
	# field 2 (the filename) accepting any arch suffix, same rule as
	# spk-up's check_pkgup. 'print' keeps $0 verbatim so the two-space
	# md5sum format is preserved.
	base="$PACKAGE-${VERSION}${EXTRAVERSION}"
	awk -v b="$base" '{
		n=$2; sub(/\.tazpkg$/,"",n)
		if (n==b) next                  # no-arch name (i486)
		m=n; sub(/-[^-]*$/,"",m)         # strip the -arch suffix
		if (m==b) next
		print
	}' $installed.$SUM > $installed.$SUM.$$ && mv $installed.$SUM.$$ $installed.$SUM
	# Drop the installed.info index line too (written by spk-add). Exact
	# field-1 match via awk so package names with regex chars (gtk+…) and
	# name prefixes (ncurses vs ncurses-dev) can't hit the wrong line.
	if [ -f $installed.info ]; then
		awk -F'\t' -v p="$PACKAGE" '$1!=p' $installed.info > $installed.info.$$ \
			&& mv $installed.info.$$ $installed.info
	fi
	log_tazpkg Removed
	status
	separator
}

#
# Output mode + planner — used only for --trame / --dry-run / --explain.
# Human flow below stays untouched.
#

[ "$explain" ] && dry_run=yes
[ "$trame" ] && dry_run=yes

# --nodeps: remove only the named packages, never their dependents. Read
# from our own arguments, not $nodeps: libtaz EXPORTS every option, so a
# parent tool's --nodeps (spk-add has one) would reach a nested spk-rm
# through the environment and silently stop its cascade.
rm_nodeps=; rm_names=; rm_fail=
for a in "$@"; do
	case "$a" in
		--nodeps) rm_nodeps=yes ;;
		--*) ;;
		*) rm_names="$rm_names $a" ;;
	esac
done

# JSON array of the words of $1.
json_list() {
	local arr="[" first=yes p
	for p in $1; do
		[ "$first" ] || arr="${arr},"; first=
		arr="${arr}\"$(json_escape "$p")\""
	done
	echo "${arr}]"
}

# Emit one trame envelope per rm call.
# Args: pkg action(removed|not-installed|would-remove) rdeps count bytes ess
# ess: the essential packages of the set (pkg + rdeps). The real removal
# refuses the whole set when it holds one, unless --force; "action" stays
# would-remove (a consumer may test it), "essential" is the flag to read.
# --nodeps adds "nodeps":true and "left_broken" (arg 7, the dependents
# kept without it); "reverse_deps" is then empty, as it means "removed
# with it" to consumers, and the counts are the package's alone.
emit_rm_trame() {
	local pkg="$1" action="$2" rdeps="$3" count="${4:-0}" bytes="${5:-0}"
	local changed=true
	[ "$action" = not-installed ] && changed=false
	local dry=true
	[ "$dry_run" ] || dry=false
	local nd=""
	[ "$rm_nodeps" ] && nd=",\"nodeps\":true,\"left_broken\":$(json_list "$7")"
	printf '{"command":"rm","package":"%s","action":"%s","changed":%s,"dry_run":%s,"reverse_deps":%s,"packages":%s,"freed_size_bytes":%s,"freed_size":"%s","essential":%s%s}\n' \
		"$(json_escape "$pkg")" "$action" "$changed" "$dry" \
		"$(json_list "$rdeps")" "$count" "$bytes" "$(human_size $bytes)" \
		"$(json_list "$6")" "$nd"
}

#
# Commands and exit
#

case "$1" in
	""|*usage|*help) usage ;;
esac

# --autoremove reaps orphans, which no package needs: --nodeps would not
# change it, so the pair is refused rather than silently ignored.
if [ "$rm_nodeps" ] && [ "$autoremove" ]; then
	msg="--nodeps cannot be used with --autoremove"
	if [ "$trame" ]; then
		printf '{"error":"%s","code":1,"command":"rm"}\n' "$msg" >&2
	elif [ "$raw" ]; then
		printf 'error\t-\t-\t%s\n' "$msg"
	else
		echo "$msg" >&2
	fi
	exit 1
fi

# --trame / --dry-run / --explain: short-circuit BEFORE the destructive
# remove() runs. Emits one envelope per pkg with the set the real removal
# would take out: the package plus its transitive reverse-deps (every
# path, --raw too, removes them, dependents first), and the essential
# ones that make it refuse without --force. Each name is planned against
# the current system, as if given alone.
if [ "$trame" ] || [ "$explain" ] || [ "$dry_run" ]; then
	# --autoremove has no package argument: report the orphan set (the
	# option-skipping loop below would otherwise emit nothing at all).
	if [ "$autoremove" ]; then
		for pkg in $(autoremove_set); do
			bytes=$(pkg_disk_bytes $pkg)
			[ "$trame" ]   && emit_rm_trame "$pkg" would-remove "" 1 "$bytes"
			[ "$explain" ] && echo "spk-rm $pkg --auto"
			[ -z "$trame" ] && [ -z "$explain" ] && \
				echo "Would remove: $pkg (orphan, $(human_size $bytes))"
		done
		exit 0
	fi
	# Nothing changes during a dry-run: one reverse-dep index serves
	# every name (built on the first installed one, 0.3 s here each).
	idx=
	for pkg in "$@"; do
		case "$pkg" in --*) continue ;; esac
		if ! is_package_installed "$pkg"; then
			[ "$trame" ]   && emit_rm_trame "$pkg" not-installed ""
			[ "$explain" ] && echo "# $pkg: not installed (no-op)"
			[ -z "$trame" ] && [ -z "$explain" ] && \
				echo "$pkg: not installed"
			continue
		fi
		[ -n "$idx" ] || idx=$(rdeps_index)
		# Full transitive closure + impact, same as the real removal.
		# --nodeps: the package alone, and who is left needing it.
		left=
		if [ "$rm_nodeps" ]; then
			rdeps_list=
			left=$(nodeps_left "$pkg" "$idx")
		else
			rdeps_list=$(rdeps_all "$pkg" "$idx")
		fi
		count=0; bytes=0
		for p in $pkg $rdeps_list; do
			is_package_installed $p || continue
			count=$((count + 1))
			bytes=$((bytes + $(pkg_disk_bytes $p)))
		done
		# Flag essential packages in the plan: the same set the real
		# removal checks before refusing (removal itself is guarded).
		ess=
		for p in $pkg $rdeps_list; do is_essential "$p" && ess="$ess $p"; done
		[ "$trame" ]   && emit_rm_trame "$pkg" would-remove "$rdeps_list" \
			"$count" "$bytes" "$ess" "$left"
		# --nodeps on each line: a bare "spk-rm X --auto" would cascade.
		nd=; [ "$rm_nodeps" ] && nd=" --nodeps"
		[ "$explain" ] && { for p in $rdeps_list $pkg; do
			is_essential "$p" && echo "spk-rm $p --auto$nd --force" \
				|| echo "spk-rm $p --auto$nd"; done; }
		[ -z "$trame" ] && [ -z "$explain" ] && {
			echo "Would remove: $pkg ($count package(s), $(human_size $bytes))"
			[ -n "$rdeps_list" ] && echo "Reverse-deps would break: $rdeps_list"
			[ -n "$left" ] && echo "Still needed by (kept, --nodeps): $left"
			[ -n "$ess" ] && echo "Essential (needs --force):$ess"
		}
	done
	[ -n "$idx" ] && rm -f "$idx"
	exit 0
fi

#
# --raw : stream a flat TSV of milestones, one line per step, for the TUI
# (and scripts). The real removal runs UNCHANGED (remove()); only its human
# output is redirected to the log so the TSV stream stays clean. Format:
# state<TAB>step<TAB>pkg<TAB>msg  with  state = step | info | ok | error | done
# Symmetric to spk-add --raw. Like the human flow it drags out the package
# plus its transitive reverse-deps (dependents first) but never prompts.
#
if [ "$raw" ]; then
	check_root "$@"
	mkdir -p "$logdir" 2>/dev/null
	date "+%F %T : spk-rm $*" >> "$logdir/raw-remove.log"
	r_ok=0; r_skip=0; r_fail=0
	# --autoremove: reap the orphan set (no package argument to iterate).
	if [ "$autoremove" ]; then
		for p in $(autoremove_set); do
			is_package_installed "$p" || continue
			printf 'step\tremove\t%s\tremoving (autoremove)\n' "$p"
			pkg=$p
			remove >>"$logdir/raw-remove.log" 2>&1
			if ! is_package_installed "$p"; then
				printf 'ok\tremove\t%s\tremoved\n' "$p"
				log "Removed package: $p (autoremove)"
				r_ok=$((r_ok + 1))
			else
				printf 'error\tremove\t%s\tfailed (see log)\n' "$p"
				r_fail=$((r_fail + 1))
			fi
		done
		printf 'done\t-\t-\t%s removed, %s failed\n' "$r_ok" "$r_fail"
		exit 0
	fi
	for arg in "$@"; do
		case "$arg" in --*) continue ;; esac

		if ! is_package_installed "$arg"; then
			printf 'ok\tskip\t%s\tnot installed\n' "$arg"
			r_skip=$((r_skip + 1)); continue
		fi

		printf 'step\tplan\t%s\tresolving reverse dependencies\n' "$arg"
		if [ "$rm_nodeps" ]; then
			# The package alone. "warn": shown, never counted as a
			# failure (front-ends fail on error/fail only).
			rdeps=
			idx=$(rdeps_index)
			left=$(nodeps_left "$arg" "$idx")
			rm -f "$idx"
			[ "$left" ] && \
				printf 'warn\tplan\t%s\tstill needed by: %s\n' "$arg" "$left"
		else
			# rdeps_all always ends with a space + newline: squeeze so a
			# package with no dependents does not print an empty line.
			rdeps=$(echo $(rdeps_all "$arg"))
			[ "$rdeps" ] && \
				printf 'info\tplan\t%s\talso removes: %s\n' "$arg" "$rdeps"
		fi

		# Refuse an essential package (directly or via rdeps) unless --force.
		if [ -z "$force" ]; then
			ess=
			for p in $arg $rdeps; do is_essential "$p" && ess="$ess $p"; done
			if [ -n "$ess" ]; then
				printf 'error\tremove\t%s\tessential, use --force:%s\n' \
					"$arg" "$(echo $ess)"
				r_fail=$((r_fail + 1)); continue
			fi
		fi

		# Dependents first (leaves before what they need), then $arg itself.
		for p in $rdeps $arg; do
			is_package_installed "$p" || continue
			printf 'step\tremove\t%s\tremoving\n' "$p"
			pkg=$p
			remove >>"$logdir/raw-remove.log" 2>&1
			if ! is_package_installed "$p"; then
				printf 'ok\tremove\t%s\tremoved\n' "$p"
				log "Removed package: $p (raw)"
				r_ok=$((r_ok + 1))
			else
				printf 'error\tremove\t%s\tfailed (see log)\n' "$p"
				r_fail=$((r_fail + 1))
			fi
		done
	done
	done_msg="$r_ok removed"
	[ "$r_skip" -gt 0 ] && done_msg="$done_msg, $r_skip skipped"
	done_msg="$done_msg, $r_fail failed"
	printf 'done\t-\t-\t%s\n' "$done_msg"
	# --nodeps is meant for scripts: say a refusal or failure by status.
	[ "$rm_nodeps" ] && [ "$r_fail" -gt 0 ] && exit 1
	exit 0
fi

#
# Handle packages
#

: ${count=0}
check_root "$@"

# --autoremove: reap auto-installed packages nothing depends on anymore.
# Stands alone (no package argument needed).
if [ "$autoremove" ]; then
	orphans=$(autoremove_set)
	if [ -z "$orphans" ]; then
		gettext "No orphan packages to remove"; newline
		exit 0
	fi
	count=0; bytes=0
	for p in $orphans; do
		count=$((count + 1)); bytes=$((bytes + $(pkg_disk_bytes $p)))
	done
	newline
	boldify $(gettext "Autoremove summary")
	separator
	gettext "Orphans     :"; colorize 31 " $(echo $orphans)"
	gettext "Packages    :"; colorize 34 " $count"
	gettext "Freed space :"; colorize 34 " $(human_size $bytes)"
	separator
	if [ -z "$auto" ]; then
		eval_gettext "Remove these \$count orphan(s)"
		if ! confirm; then
			gettext "Autoremove cancelled"; newline
			exit 0
		fi
	fi
	for p in $orphans; do
		is_package_installed $p || continue
		pkg=$p; remove
		log "Removed package: $p (autoremove)"
	done
	exit 0
fi

for arg in $@
do
	# Skip options
	case "$arg" in
		--*) continue
	esac
	# Be sure package is installed
	if ! is_package_installed $arg; then
		echo -n "$(boldify $arg) "
		gettext "package is not installed"; newline
		continue
	fi

	# Full removal set: the package plus its transitive reverse-deps.
	# Removing only $arg would break everything that depends on it, so
	# they are dragged out too — but the user is warned and must confirm.
	# --nodeps: $arg alone; the dependents it leaves are named instead.
	left=
	if [ "$rm_nodeps" ]; then
		rdeps=
		idx=$(rdeps_index)
		left=$(nodeps_left $arg "$idx")
		rm -f "$idx"
	else
		rdeps=$(rdeps_all $arg)
	fi

	# Refuse if the removal set contains an essential package (directly or
	# as a dragged-in reverse dep). --force overrides.
	if [ -z "$force" ]; then
		ess=
		for p in $arg $rdeps; do is_essential "$p" && ess="$ess $p"; done
		if [ -n "$ess" ]; then
			gettext "REFUSED: essential package(s), use --force:"
			colorize 31 " $(echo $ess)"; newline
			rm_fail=yes
			continue
		fi
	fi

	# Tally impacted packages and the disk space removal will free.
	pkgs_total=0; bytes=0
	for p in $arg $rdeps; do
		is_package_installed $p || continue
		pkgs_total=$((pkgs_total + 1))
		bytes=$((bytes + $(pkg_disk_bytes $p)))
	done

	# Impact summary — shown BEFORE anything is touched.
	newline
	boldify $(gettext "Removal summary")
	separator
	gettext "Package      :"; colorize 34 " $arg"
	if [ "$rdeps" ]; then
		gettext "Also removes :"; colorize 31 " $(echo $rdeps)"
	fi
	if [ "$left" ]; then
		gettext "Needed by    :"; colorize 33 " $left"
	fi
	gettext "Packages     :"; colorize 34 " $pkgs_total"
	gettext "Freed space  :"; colorize 34 " $(human_size $bytes)"
	separator

	# Confirm by default — removal is destructive and may cascade.
	# --auto skips the prompt for scripts. Default answer is No.
	if [ -z "$auto" ]; then
		if [ -z "$rm_nodeps" ]; then
			eval_gettext "Remove these \$pkgs_total package(s)"
		elif [ "$left" ]; then
			eval_gettext "Remove only \$arg, keeping the packages that need it"
		else
			eval_gettext "Remove only \$arg"
		fi
		if ! confirm; then
			gettext "Removal cancelled"; newline
			continue
		fi
	fi

	# Remove dependents first (leaves before what they need), then $arg.
	for rdep in $rdeps; do
		is_package_installed $rdep || continue
		pkg=$rdep; remove
		log "Removed package: $rdep"
		count=$(($count + 1))
	done
	pkg=$arg; remove
	log "Removed package: $arg"
	count=$(($count + 1))
	# --nodeps: a warning, not an error, for what now lacks $arg.
	if [ "$rm_nodeps" ]; then
		if is_package_installed $arg; then
			rm_fail=yes
		elif [ "$left" ]; then
			gettext "WARNING: left without"; colorize 33 " $arg: $left"
		fi
	fi
done

# Show all new counted packages in verbose mode
if [ "$verbose" ]; then
	gettext "Removed packages:"; colorize 34 " $count"
fi

# --nodeps is meant for scripts: a refused or failed removal says so by
# status (not installed is not a failure). Other runs keep exit 0.
[ "$rm_nodeps" ] && [ "$rm_fail" ] && exit 1
exit 0
