xref: /freebsd/usr.sbin/bsdconfig/share/packages/packages.subr (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
1if [ ! "$_PACKAGES_PACKAGES_SUBR" ]; then _PACKAGES_PACKAGES_SUBR=1
2#
3# Copyright (c) 2013-2016 Devin Teske
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27#
28############################################################ INCLUDES
29
30BSDCFG_SHARE="/usr/share/bsdconfig"
31. $BSDCFG_SHARE/common.subr || exit 1
32f_dprintf "%s: loading includes..." "$0"
33f_include $BSDCFG_SHARE/dialog.subr
34f_include $BSDCFG_SHARE/device.subr
35f_include $BSDCFG_SHARE/media/common.subr
36f_include $BSDCFG_SHARE/packages/categories.subr
37f_include $BSDCFG_SHARE/packages/index.subr
38f_include $BSDCFG_SHARE/packages/musthavepkg.subr
39f_include $BSDCFG_SHARE/strings.subr
40
41BSDCFG_LIBE="/usr/libexec/bsdconfig"
42f_include_lang $BSDCFG_LIBE/include/messages.subr
43
44############################################################ CONFIGURATION
45
46#
47# How many packages to display (maximum) per dialog menubox.
48#
49: ${PACKAGE_MENU_PAGESIZE:=2000}
50
51############################################################ GLOBALS
52
53#
54# Package extensions to try
55#
56PACKAGE_EXTENSIONS=".txz .tbz .tbz2 .tgz"
57
58#
59# Variables used to track runtime states
60#
61PACKAGES_DETECTED=	# Boolean (NULL/non-NULL); detected installed packages?
62PACKAGE_CATEGORIES=	# List of package categories parsed from INDEX
63SELECTED_PACKAGES=	# Packages selected by user in [X]dialog(1) interface
64
65#
66# Options
67#
68[ "${SHOW_DESC+set}" ] || SHOW_DESC=1
69
70############################################################ FUNCTIONS
71
72# eval f_package_accent_category_menu $var_to_set $CATEGORY_MENU_LIST
73#
74# Accent the CATEGORY_MENU_LIST produced by f_index_read() (see
75# packages/index.subr). Accented information includes adding an asterisk to the
76# category name if its index has been cached, adding the number of installed
77# packages for each category, and adding the number _selected_ packages for
78# each category.
79#
80# NOTE: The reason `eval' is recommended/shown for the syntax above is because
81# the $CATEGORY_MENU_LIST generated by f_index_read() is meant to be expanded
82# prior to execution (it contains a series of pre-quoted strings which act as
83# the interpolated command arguments).
84#
85f_package_accent_category_menu()
86{
87	local var_to_set="$1" category cat desc help varcat menu_buf n
88	shift 1 # var_to_set
89	while [ $# -gt 0 ]; do
90		category="${1%\*}" desc="${2%%; *}" help="$3"
91		shift 3 # cat/desc/help
92
93		cat="${category# }" # Trim lead space inserted by sort-method
94		f_str2varname "$cat" varcat
95
96		# Add number of installed packages for this category (if any)
97		n=0
98		case "$cat" in
99		"$msg_all") debug= f_getvar "_All_ninstalled" n ;;
100		         *) debug= f_getvar "_${varcat}_ninstalled" n ;;
101		esac &&
102		[ $n -ge 1 ] && desc="$desc; $n $msg_installed_lc"
103
104		# Add number of selected packages for this category (if any)
105		n=0
106		case "$cat" in
107		"$msg_all") debug= f_getvar "_All_nselected" n ;;
108		         *) debug= f_getvar "_${varcat}_nselected" n ;;
109		esac &&
110		[ $n -ge 1 ] && desc="$desc; $n $msg_selected"
111
112		# Re-Add asterisk to the category if its index has been cached
113		f_isset _index_page_${varcat}_1 && category="$category*"
114
115		# Update buffer with modified elements
116		menu_buf="$menu_buf
117		'$category' '$desc' '$help'" # End-Quote
118	done
119	setvar "$var_to_set" "$menu_buf" # return our buffer
120}
121
122# f_package_select $package ...
123#
124# Add $package to the list of tracked/selected packages. If $package is already
125# being tracked (already apears in $SELECTED_PACKAGES), this function amounts
126# to having no effect.
127#
128f_package_select()
129{
130	local package pkgsel
131	while [ $# -gt 0 ]; do
132		package="$1"
133		shift 1 # package
134		for pkgsel in $SELECTED_PACKAGES; do
135			[ "$package" = "$pkgsel" ] && return $SUCCESS
136		done
137		SELECTED_PACKAGES="$SELECTED_PACKAGES $package"
138		f_dprintf "Added %s to selection list" "$package"
139	done
140	SELECTED_PACKAGES="${SELECTED_PACKAGES# }" # Trim leading space
141}
142
143# f_package_deselect $package ...
144#
145# Remove $package from the list of tracked/selected packages. If $package is
146# not being tracked (doesn't appear in $SELECTED_PACKAGES), this function
147# amounts to having no effet.
148#
149f_package_deselect()
150{
151	local package pkgsel
152	while [ $# -gt 1 ]; do
153		local new_list=""
154		package="$1"
155		shift 1 # package
156		for pkgsel in $SELECTED_PACKAGES; do
157			[ "$pkgsel" = "$package" ] && continue
158			new_list="$new_list${new_list:+ }$pkgsel"
159		done
160		SELECTED_PACKAGES="$new_list"
161		f_dprintf "Removed %s from selection list" "$package"
162	done
163}
164
165# f_package_detect_installed
166#
167# Detect installed packages. Currently this uses pkg-query(8) for querying
168# entries and marks each entry as an installed/selected package.
169#
170f_package_detect_installed()
171{
172	local package varpkg
173	for package in $( pkg query "%n-%v" ); do
174		f_str2varname $package varpkg
175		export _mark_$varpkg=X # exported for awk(1) ENVIRON[]
176		f_package_select $package
177	done
178}
179
180# f_package_calculate_totals
181#
182# Calculate number of installed/selected packages for each category listed in
183# $PACKAGE_CATEGORIES (the number of installed packages for $category is stored
184# as $_${varcat}_ninstalled -- where $varcat is the product of `f_str2varname
185# $category varcat' -- and number selected packages as $_${varcat}_nselected).
186# Also calculates the total number of installed/selected packages stored as
187# $_All_ninstalled and $_All_nselected.
188#
189# Calculations are performed by checking "marks". A "mark" is stored as
190# $_mark_$varpkg -- where $varpkg is the product of `f_str2varname $package
191# varpkg'. A mark can be "X" for an installed package, `I' for a package that
192# is marked for installation, "R" for a package that is marked for re-install,
193# and "U" for a package that is marked for uninstallation. If a package mark is
194# NULL or a single space (e.g., " "), the package is considered to be NOT
195# selected (and therefore does not increment the counts calculated herein).
196#
197f_package_calculate_totals()
198{
199	local pkg varpkg mark cat varcat pkgcat n tselected=0 tinstalled=0
200	for cat in $PACKAGE_CATEGORIES; do
201		f_str2varname $cat varcat
202		setvar _${varcat}_ninstalled=0
203		setvar _${varcat}_nselected=0
204	done
205	for pkg in $SELECTED_PACKAGES; do
206		f_str2varname $pkg varpkg
207		mark=
208		f_getvar _mark_$varpkg mark
209		case "$mark" in
210		""|" ") : ;;
211		X) tinstalled=$(( $tinstalled + 1 )) ;;
212		*) tselected=$(( $tselected + 1 ))
213		esac
214		f_getvar _categories_$varpkg pkgcat
215		for cat in $pkgcat; do
216			f_str2varname $cat varcat
217			case "$mark" in
218			""|" ") : ;;
219			X) debug= f_getvar _${varcat}_ninstalled n
220			   setvar _${varcat}_ninstalled $(( $n + 1 )) ;;
221			*) debug= f_getvar _${varcat}_nselected n
222			   setvar _${varcat}_nselected $(( $n + 1 ))
223			esac
224		done
225	done
226	_All_nselected=$tselected
227	_All_ninstalled=$tinstalled
228}
229
230# f_package_calculate_rundeps
231#
232# Update package dependencies by first unmarking all dependencies and then
233# re-marking all dependencies of packages marked for either install ("I") or
234# re-install ("R").
235#
236f_package_calculate_rundeps()
237{
238	local pkg varpkg mark rundeps dep vardep
239
240	#
241	# First unmark all the existing run-dependencies
242	#
243	f_dprintf "Unselecting package run-dependencies..."
244	for pkg in $SELECTED_PACKAGES; do
245		f_str2varname $pkg varpkg
246		mark=
247		debug= f_getvar _mark_$varpkg mark
248		# Only unmark if it's marked as a Dependency
249		if [ "$mark" = "D" ]; then
250			f_dprintf "%s unselected" $pkg
251			unset _mark_$varpkg
252			f_package_deselect $pkg
253		fi
254	done
255
256	#
257	# Processes selected packages, adding dependencies
258	#
259	f_dprintf "Re-selecting package run-dependencies..."
260	for pkg in $SELECTED_PACKAGES; do
261		f_str2varname $pkg varpkg
262		mark=
263		debug= f_getvar _mark_$varpkg mark
264		# Skip pkg unless marked for [Re-]Install
265		[ "$mark" = "I" -o "$mark" = "R" ] || continue
266		f_getvar _rundeps_$varpkg rundeps
267		for dep in $rundeps; do
268			f_str2varname $dep vardep
269			mark=
270			debug= f_getvar _mark_$vardep mark
271			# Skip dep if already marked
272			[ "${mark:- }" = " " ] || continue
273			export _mark_$vardep="D"
274			f_package_select $dep
275		done
276	done
277
278	f_dprintf "Finished recalculating dependencies."
279}
280
281# f_package_menu_categories $var_to_set $defaultitem
282#
283# Dislay the menu of package categories, complete with package counts for each
284# category, accents, and other miscellany. If $defaultitem is non-NULL and
285# matches one of the existing menu-items, it will be pre-highlighted in the
286# menu dialog (HINT: Use f_dialog_menutag_fetch() to populate a local variable
287# that is passed as $defaultitem to highlight the user's last selection).
288#
289f_package_menu_categories()
290{
291	local var_to_get="$1" defaultitem="$2"
292	local prompt="$msg_please_select_a_category_to_display"
293	local menu_list="
294		'> $msg_review' '$msg_review_desc' '$msg_review_help'
295	" # End-Quote
296	local hline=
297
298	f_package_calculate_rundeps
299		# updates package mark variables and SELECTED_PACKAGES
300	f_package_calculate_totals
301		# creates _{varcat}_ninstalled and _{varcat}_nselected
302
303	local category_list
304	debug= f_getvar "$var_to_get" category_list || return $DIALOG_CANCEL
305
306	# Accent the category menu list with ninstalled/nselected
307	eval f_package_accent_category_menu category_list $category_list
308
309	# Add list of categories to menu list
310	menu_list="$menu_list $category_list"
311
312	local height width rows
313	eval f_dialog_menu_with_help_size height width rows \
314	                                  \"\$DIALOG_TITLE\"     \
315	                                  \"\$DIALOG_BACKTITLE\" \
316	                                  \"\$prompt\"           \
317	                                  \"\$hline\"            \
318	                                  $menu_list
319	local menu_choice
320	menu_choice=$( eval $DIALOG \
321		--title \"\$DIALOG_TITLE\"         \
322		--backtitle \"\$DIALOG_BACKTITLE\" \
323		--hline \"\$hline\"                \
324		--item-help                        \
325		--default-item \"\$defaultitem\"   \
326		--ok-label \"$msg_select\"         \
327		--cancel-label \"$msg_cancel\"     \
328		--menu \"\$prompt\"                \
329		$height $width $rows               \
330		$menu_list                         \
331		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
332	)
333	local retval=$?
334	f_dialog_menutag_store -s "$menu_choice"
335	return $retval
336}
337
338# f_package_index_get_page $category $page [$var_to_set [$var_to_get]]
339#
340# Obtain a [potentially cached] page of the INDEX file for a given $category.
341# If $page is 1 and the cache has not yet been generated, the cache-generating
342# function f_index_extract_pages() (above) is called to generate all pages
343# (not just the requested page) in cache before returning the requested page.
344# If $page is not 1 and there is no cached page, failure status is returned.
345#
346f_package_index_get_page()
347{
348	local category="$1" page="$2" var_to_set="$3" var_to_get="$4" varcat
349	f_str2varname "$category" varcat
350	if ! debug= f_getvar "_index_page_${varcat}_$page" $var_to_set &&
351	   [ "$page" = "1" ]
352	then
353		f_show_info "$msg_building_package_menus"
354		local pagesize="$PACKAGE_MENU_PAGESIZE"
355		f_index_extract_pages "${var_to_get:-PACKAGE_INDEX}" \
356			_index_page_${varcat} "$pagesize" "$category"
357		debug= f_getvar _index_page_${varcat}_$page $var_to_set
358
359		# Update category default-item because now we're cached
360		[ $page -eq 1 ] &&
361		    category_defaultitem="${category_defaultitem%\*}*"
362	else
363		return $FAILURE
364	fi
365}
366
367# f_package_menu_select $category [$page [$defaultitem]]
368#
369# Display list of packages for $category, optionally $page N and with a default
370# item selected. If $page is omitted, the first page is displayed (but this
371# only matters if there are multiple pages; which is determined by the global
372# maximum $PACKAGE_MENU_PAGESIZE).
373#
374# On success, if the user doesn't press ESC or choose Cancel, use
375# f_dialog_menuitem_fetch() to populate a local variable with the item (not
376# tag) corresponding to the user's selection. The tag portion of the user's
377# selection is available through f_dialog_menutag_fetch().
378#
379f_package_menu_select()
380{
381	local __funcname=f_package_menu_deselect
382	local category="$1" page="${2:-1}"
383	local prompt= # Calculated below
384	local menu_list # Calculated below
385	local defaultitem="$3"
386	local hline="$hline_arrows_tab_punc_enter"
387
388	f_isinteger "$page" || return $DIALOG_CANCEL
389
390	local varcat
391	f_str2varname "$category" varcat
392
393	# Get number of packages for this category
394	local npkgs=0
395	case "$category" in
396	"$msg_all"|"") npkgs="${_npkgs:-0}" ;;
397	*) f_getvar _npkgs_$varcat npkgs
398	esac
399
400	# Calculate number of pages
401	local npages=$(( ${npkgs:=0} / $PACKAGE_MENU_PAGESIZE ))
402
403	# Add a page to the pagecount if not evenly divisible
404	[ $(( $npages * $PACKAGE_MENU_PAGESIZE )) -lt $npkgs ] &&
405		npages=$(( $npages + 1 ))
406
407	# Print some debugging information
408	f_dprintf "f_package_menu_select: category=[%s] npkgs=%u npages=%u" \
409	          "$category" "$npkgs" "$npages"
410
411	local add_prev="" add_next=""
412	local previous_page="$msg_previous_page" next_page="$msg_next_page"
413	if [ $page -gt 1 ]; then
414		add_prev=1
415		# Accent the `Previous Page' item with an asterisk
416		# if the page-before-previous is loaded/cached
417		f_isset _index_page_${varcat}_$(( $page - 1 )) &&
418			previous_page="$previous_page*"
419	fi
420	if [ $page -lt $npages ]; then
421		add_next=1
422		# Accent the `Next Page' item with an asterisk
423		# if the page-after-next is loaded/cached
424		f_isset _index_page_${varcat}_$(( $page + 1 )) &&
425			next_page="$next_page*"
426	fi
427
428	local index_page __index
429	if [ "$category" = "$msg_all" ]; then
430		f_eval_catch -k __index $__funcname pkg \
431			"pkg rquery -a '%s'"  "%n|%o||%c"
432	else
433		f_eval_catch -k __index $__funcname pkg \
434			"pkg rquery -g '%s' '%s/\*'"  "%n|%o||%c" "$category"
435	fi
436	f_package_index_get_page "$category" $page index_page __index
437
438	menu_list="
439		${add_prev:+'> $previous_page' '' ${SHOW_DESC:+''}}
440		${add_next:+'> $next_page' '' ${SHOW_DESC:+''}}
441	$(
442		export SHOW_DESC
443		export VALID_VARNAME_CHARS
444		echo "$index_page" | awk -F'|' -v view="port" '
445		BEGIN {
446			valid_chars = ENVIRON["VALID_VARNAME_CHARS"]
447			prefix = ""
448		}
449		{
450			cur_prefix = tolower(substr($1, 1, 1))
451			printf "'\''"
452			if ( prefix != cur_prefix )
453				prefix = cur_prefix
454			else
455				printf " "
456			package = $1
457			if ( view == "port" )
458				desc = $2
459			varpkg = package
460			gsub("[^" valid_chars "]", "_", varpkg)
461			mark = ENVIRON["_mark_" varpkg]
462			if ( ! mark ) mark = " "
463			printf "%s'\'' '\''[%c] %s'\''",
464			       package, mark, desc
465			if ( ENVIRON["SHOW_DESC"] ) {
466				help = $4
467				gsub(/'\''/, "'\''\\'\'\''", help)
468				printf " '\''%s'\''", help
469			}
470			printf "\n"
471		}'
472	)
473		${add_prev:+'> $previous_page' '' ${SHOW_DESC:+''}}
474		${add_next:+'> $next_page' '' ${SHOW_DESC:+''}}
475	" # End-Quote
476
477	# Accept/Translate i18n "All" but other category names must
478	# match tree definitions from INDEX, ports, FTP, etc.
479	case "$category" in
480	"$msg_all"|"") f_category_desc_get "All" prompt ;;
481	            *) f_category_desc_get "$category" prompt ;;
482	esac
483	f_sprintf prompt "%s $msg_page_of_npages" "$prompt" "$page" "$npages"
484
485	local mheight mwidth mrows
486	eval f_dialog_menu${SHOW_DESC:+_with_help}_size mheight mwidth mrows \
487	        	\"\$DIALOG_TITLE\" \"\$DIALOG_BACKTITLE\" \
488	        	\"\$prompt\" \"\$hline\" $menu_list
489	local iheight iwidth
490	f_dialog_infobox_size iheight iwidth \
491	         	"$DIALOG_TITLE" "$DIALOG_BACKTITLE" \
492	         	"$msg_processing_selection"
493
494	local menu_choice
495	menu_choice=$( eval $DIALOG \
496		--title \"\$DIALOG_TITLE\"         \
497		--backtitle \"\$DIALOG_BACKTITLE\" \
498		--hline \"\$hline\"                \
499		--keep-tite                        \
500		--ok-label \"$msg_select\"         \
501		--cancel-label \"$msg_back\"       \
502		${SHOW_DESC:+--item-help}          \
503		--default-item \"\$defaultitem\"   \
504		--menu \"\$prompt\"                \
505		$mheight $mwidth $mrows            \
506		$menu_list                         \
507		--and-widget                       \
508		${USE_XDIALOG:+--no-buttons}       \
509		--infobox \"\$msg_processing_selection\" \
510		$iheight $iwidth                   \
511		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
512	)
513	local retval=$?
514	f_dialog_data_sanitize menu_choice
515	f_dialog_menutag_store "$menu_choice"
516
517	if [ $retval -eq $DIALOG_OK ]; then
518		local item
519		item=$( eval f_dialog_menutag2item${SHOW_DESC:+_with_help} \
520		             	\"\$menu_choice\" $menu_list )
521		f_dialog_menuitem_store "$item"
522	fi
523
524	return $retval
525}
526
527# f_package_menu_deselect $package
528#
529# Display a menu, asking the user what they would like to do with $package
530# with regard to "deselecting" an already installed package. Choices include
531# uninstall, re-install, or cancel (leave $package marked as installed).
532# Returns success if the user does not press ESC or choose Cnacel. Use the
533# f_dialog_menutag_fetch() function upon success to retrieve the user's choice.
534#
535f_package_menu_deselect()
536{
537	local package="$1"
538	local prompt # Calculated below
539	local menu_list="
540		'X $msg_installed' '$msg_installed_desc'
541		'R $msg_reinstall' '$msg_reinstall_desc'
542		'U $msg_uninstall' '$msg_uninstall_desc'
543	" # End-Quote
544	local hline="$hline_alnum_arrows_punc_tab_enter"
545
546	f_sprintf prompt "$msg_what_would_you_like_to_do_with" "$package"
547
548	local height width rows
549	eval f_dialog_menu_size height width rows \
550	                        \"\$DIALOG_TITLE\"     \
551	                        \"\$DIALOG_BACKTITLE\" \
552	                        \"\$prompt\"           \
553	                        \"\$hline\"            \
554	                        $menu_list
555	local menu_choice
556	menu_choice=$( eval $DIALOG \
557		--title \"\$DIALOG_TITLE\"         \
558		--backtitle \"\$DIALOG_BACKTITLE\" \
559		--hline \"\$hline\"                \
560		--ok-label \"$msg_select\"         \
561		--cancel-label \"$msg_cancel\"     \
562		--menu \"\$prompt\"                \
563		$height $width $rows               \
564		$menu_list                         \
565		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
566	)
567	local retval=$?
568	f_dialog_menutag_store -s "$menu_choice"
569	return $retval
570}
571
572# f_package_review
573#
574# Display a review screen, showing selected packages and what they are marked
575# for, before proceeding (if the user does not press ESC or choose Cancel) to
576# operate on each selection. Returns error if no packages have been selected,
577# or the user has pressed ESC, or if they have chosen Cancel.
578#
579f_package_review()
580{
581	local funcname=f_package_review
582	local prompt # Calculated below
583	local menu_list # Calculated below
584	local hline="$hline_alnum_arrows_punc_tab_enter"
585
586	f_dprintf "$funcname: SELECTED_PACKAGES=[%s]" "$SELECTED_PACKAGES"
587
588	f_sprintf prompt "$msg_reviewing_selected_packages" "$_All_nselected"
589
590	local package varpkg mark
591	for package in $SELECTED_PACKAGES; do
592		mark=
593		f_str2varname "$package" varpkg
594		f_getvar _mark_$varpkg mark
595		[ "$mark" -a ! "${mark#[IRUD]}" ] || continue
596		menu_list="$menu_list
597			'$mark' '$package'
598		" # End-Quote
599	done
600	if [ ! "$menu_list" ]; then
601		f_show_msg "$msg_no_packages_were_selected_for_extraction"
602		return $DIALOG_CANCEL # Might have selected this by accident
603	fi
604	menu_list=$( echo "$menu_list" | sort )
605
606	local height width rows
607	eval f_dialog_menu_size height width rows \
608	                        \"\$DIALOG_TITLE\"     \
609	                        \"\$DIALOG_BACKTITLE\" \
610	                        \"\$prompt\"           \
611	                        \"\$hline\"            \
612	                        $menu_list
613
614	# Show the review menu (ignore menu choice)
615	eval $DIALOG \
616		--title \"\$DIALOG_TITLE\"         \
617		--backtitle \"\$DIALOG_BACKTITLE\" \
618		--hline \"\$hline\"                \
619		--ok-label \"\$msg_proceed\"       \
620		--cancel-label \"\$msg_cancel\"    \
621		--menu \"\$prompt\"                \
622		$height $width $rows               \
623		$menu_list                         \
624		2> /dev/null || return $?
625			# Return if the user pressed ESC or chose Cancel/No
626
627	#
628	# Process each of the selected packages:
629	# + First, process packages marked for Install.
630	# + Second, process packages marked for Re-install.
631	# + Finally, process packages marked for Uninstall.
632	#
633	for package in $SELECTED_PACKAGES; do
634		mark=
635		f_str2varname "$package" varpkg
636		debug= f_getvar _mark_$varpkg mark
637		[ "$mark" = "I" ] || continue
638		f_dprintf "$funcname: Installing %s package" "$package"
639		f_package_add "$package"
640	done
641	for package in $SELECTED_PACKAGES; do
642		mark=
643		f_str2varname "$package" varpkg
644		debug= f_getvar _mark_$varpkg mark
645		[ "$mark" = "R" ] || continue
646		f_dprintf "$funcname: Reinstalling %s package" "$package"
647		f_package_reinstall "$package"
648	done
649	for package in $SELECTED_PACKAGES; do
650		mark=
651		f_str2varname "$package" varpkg
652		debug= f_getvar _mark_$varpkg mark
653		[ "$mark" = "U" ] || continue
654		f_dprintf "$funcname: Uninstalling %s package" "$package"
655		f_package_delete "$package" || continue
656		f_package_deselect "$package"
657	done
658
659	return $DIALOG_OK
660}
661
662# f_package_config
663#
664# Allow the user to configure packages and install them. Initially, a list of
665# package categories is loaded/displayed. When the user selects a category,
666# the menus for that category are built (unlike sysinstall which built all
667# category menus up-front -- which also took forever, despite the fact that
668# few people visit more than a couple of categories each time).
669#
670f_package_config()
671{
672	# Did we get an INDEX?
673	f_index_initialize || return $FAILURE
674		# Creates following variables (indirectly via f_index_read())
675		#   CATEGORY_MENU_LIST _categories_{varpkg} _rundeps_{varpkg}
676		#   PACKAGE_CATEGORIES _npkgs
677
678	f_show_info "$msg_building_package_main_menu"
679
680	# Detect installed packages (updates marks/SELECTED_PACKAGES)
681	f_package_detect_installed
682	export PACKAGES_DETECTED=1 # exported for awk(1) ENVIRON[]
683
684	local retval category varcat defaultitem category_defaultitem=""
685	while :; do
686		# Display the list of package categories
687		f_package_menu_categories \
688			CATEGORY_MENU_LIST "$category_defaultitem"
689		retval=$?
690		f_dialog_menutag_fetch category
691		f_dprintf "retval=%u mtag=[%s]" $retval "$category"
692		category_defaultitem="$category"
693
694		[ $retval -eq $DIALOG_OK ] || break
695
696		# Maybe the user chose an action (like `Review')
697		case "$category" in
698		"> $msg_review")
699			f_package_review && break
700			continue ;;
701		"> "*)
702			continue
703		esac
704
705		# Anything else is a package category
706
707		category=${category# } # Trim leading space if present
708		category=${category%\*} # Trim trailing asterisk if present
709
710		f_str2varname "$category" varcat
711
712		local page package varpkg mark menu_choice
713		while :; do
714			# Display the list of packages for selected category
715			page=1 defaultitem=""
716			f_getvar _defaultitem_$varcat defaultitem
717			f_getvar _defaultpage_$varcat page
718			f_package_menu_select \
719				"$category" "${page:=1}" "$defaultitem"
720			retval=$?
721			f_dialog_menutag_fetch menu_choice
722			f_dprintf "retval=%u mtag=[%s]" $retval "$menu_choice"
723
724			# NOTE: When --and-widget is used only ESC will cause
725			# dialog(1) to return without going to the next widget.
726			# This is alright in our case as we can still detect
727			# the Cancel button because stdout will be NULL.
728			# Alternatively, Xdialog(1) will terminate with 1
729			# if/when Cancel is chosen on any widget.
730			if [ $retval -eq $DIALOG_ESC -o ! "$menu_choice" ]
731			then
732				break
733			elif [ $retval -eq $DIALOG_CANCEL ]; then
734				# Using X11, Xdialog(1) returned 1 for Cancel
735				f_show_msg "%s" "$menu_choice"
736				break
737			elif [ $retval -ne $DIALOG_OK ]; then
738				# X11-related error occurred using Xdialog(1)
739				f_show_msg "%s" "$menu_choice"
740				break
741			fi
742
743			defaultitem="$menu_choice"
744
745			# NOTE: f_package_menu_select() does not show the
746			# `Previous Page' or `Next Page' items unless needed
747			case "$menu_choice" in
748			"> $msg_previous_page"|"> $msg_previous_page*")
749				page=$(( $page - 1 ))
750				setvar _defaultpage_$varcat $page
751				# Update default-item to match accent that will
752				# be applied by f_package_menu_select(); if the
753				# page-before-prev is cached, add an asterisk.
754				if f_isset \
755					_index_page_${varcat}_$(( $page - 1 ))
756				then
757					defaultitem="${defaultitem%\*}*"
758				else
759					defaultitem="${defaultitem%\*}"
760				fi
761				setvar _defaultitem_$varcat "$defaultitem"
762				continue ;;
763			"> $msg_next_page"|"> $msg_next_page*")
764				page=$(( $page + 1 ))
765				setvar _defaultpage_$varcat $page
766				# Update default-item to match accent that will
767				# be applied by f_package_menu_select(); if the
768				# page-after-next is cached, add an asterisk.
769				if f_isset \
770					_index_page_${varcat}_$(( $page + 1 ))
771				then
772					defaultitem="${defaultitem%\*}*"
773				else
774					defaultitem="${defaultitem%\*}"
775				fi
776				setvar _defaultitem_$varcat "$defaultitem"
777				continue ;;
778			"> "*) # Unknown navigation/action item
779				setvar _defaultpage_$varcat $page
780				continue ;; # Do not treat as a package
781			*)
782				setvar _defaultitem_$varcat "$defaultitem"
783			esac
784
785			# Treat any other selection as a package
786			package="${menu_choice# }" # Trim leading space
787			f_str2varname $package varpkg
788			f_dialog_menuitem_fetch mark
789			mark="${mark#?}"
790			mark="${mark%%\] *}"
791			case "$mark" in
792			"I")
793				mark=" "
794				f_package_deselect $package
795				;;
796			" "|"D")
797				mark="I"
798				f_package_select $package
799				;;
800			"X"|"R"|"U")
801				f_package_menu_deselect $package || continue
802				f_dialog_menutag_fetch menu_choice
803				case "$menu_choice" in
804				"X $msg_installed")
805					f_package_deselect "$package"
806					mark="X"
807					;;
808				"R $msg_reinstall")
809					f_package_select "$package"
810					mark="R"
811					;;
812				"U $msg_uninstall")
813					f_package_select "$package"
814					mark="U"
815					;;
816				esac
817				;;
818			esac
819			export _mark_$varpkg="$mark"
820				# NOTE: exported for awk(1) ENVIRON[]
821		done
822	done
823}
824
825# f_package_add $package_name [$depended]
826#
827# Like f_package_extract(), but assumes current media device and chases deps.
828# Note that $package_name should not contain the archive suffix (e.g., `.tbz').
829# If $depended is present and non-NULL, the package is treated as a dependency
830# (in this function, dependencies are not handled any differently, but the
831# f_package_extract() function is passed this value and it displays a different
832# message when installing a dependency versus non-dependency).
833#
834f_package_add()
835{
836	local name="$1" depended="$2" status=$SUCCESS retval
837
838	local alert=f_show_msg no_confirm=
839	f_getvar $VAR_NO_CONFIRM no_confirm
840	[ "$no_confirm" ] && alert=f_show_info
841
842	if ! { [ "$name" ] || { f_getvar $VAR_PACKAGE name && [ "$name" ]; }; }
843	then
844		f_dprintf "packageAdd: %s" \
845		          "$msg_no_package_name_passed_in_package_variable"
846		return $FAILURE
847	fi
848
849	{ # Verify and initialize device media if-defined
850		f_media_verify &&
851		f_device_init device_media &&
852		f_index_initialize
853	} || return $FAILURE
854
855	# Now we have (indirectly via f_index_read()):
856	#   CATEGORY_MENU_LIST _categories_{varpkg} _rundeps_{varpkg}
857	#   PACKAGE_CATEGORIES _npkgs
858
859	local varpkg
860	f_str2varname "$name" varpkg
861
862	# Just as-in the user-interface (opposed to scripted-use), only allow
863	# packages with at least one category to be recognized.
864	#
865	local pkgcat=
866	if ! f_getvar _categories_$varpkg pkgcat || [ ! "$pkgcat" ]; then
867		# $pkg may be a partial name, search the index (this is slow)
868		f_index_search PACKAGE_INDEX $name name
869		if [ ! "$name" ]; then
870			f_show_msg \
871			    "$msg_sorry_package_was_not_found_in_the_index" \
872			    "$name"
873			return $FAILURE
874		fi
875		f_str2varname "$name" varpkg
876	fi
877
878	# If invoked through the scripted interface, we likely have not yet
879	# detected the installed packages -- something we should do only once.
880	#
881	if [ ! "$PACKAGES_DETECTED" ]; then
882		f_dprintf "f_package_add: Detecting installed packages"
883		f_package_detect_installed
884		export PACKAGES_DETECTED=1 # exported for awk(1) ENVIRON[]
885	fi
886	# Now we have: _mark_{varpkg}=X for all installed packages
887
888	#
889	# Since we're maintaining data structures for installed packages,
890	# short-circuit the package dependency checks if the package is already
891	# installed. This prevents wasted cycles, minor delays between package
892	# extractions, and worst-case an infinite loop with a certain faulty
893	# INDEX file.
894	#
895	local mark=
896	f_getvar _mark_$varpkg mark && [ "$mark" = "X" ] && return $SUCCESS
897
898	local dep vardep rundeps=
899	f_getvar _rundeps_$varpkg rundeps
900	for dep in $rundeps; do
901		f_str2varname "$dep" vardep
902
903		# Skip dependency if already installed
904		mark=
905		f_getvar _mark_$vardep mark && [ "$mark" = "X" ] && continue
906
907		# Just as-in the user-interface (opposed to scripted-use), only
908		# allow packages with at least one category to be recognized.
909		#
910		local depcat=
911		if ! f_getvar _categories_$vardep depcat || [ ! "$depcat" ]
912		then
913			$alert "$msg_required_package_not_found" "$dep"
914			[ "$no_confirm" ] && sleep 2
915		fi
916
917		f_package_add "$dep"
918		retval=$?
919		if [ $retval -ne $SUCCESS ]; then
920			status=$(( $status | $retval ))
921
922			# XXX package could be on a future disc volume
923			# XXX (not supporting multiple disc volumes yet)
924
925			$alert "$msg_loading_of_dependent_package_failed" \
926			       "$dep"
927			[ "$no_confirm" ] && sleep 2
928		fi
929	done
930	[ $status -eq $SUCCESS ] || return $status
931
932	#
933	# Done with the deps? Try to load the real m'coy.
934	#
935
936	f_package_extract device_media "$name" "$depended"
937	retval=$?
938	if [ $retval -ne $SUCCESS ]; then
939		status=$(( $status | $retval ))
940	else
941		setvar _mark_$varpkg X
942	fi
943
944	return $status
945}
946
947# f_package_extract $device $name [$depended]
948#
949# Extract a package based on a namespec and media device. If $depended is
950# present and non-NULL, the notification displayed while installing the package
951# has "as a dependency" appended.
952#
953f_package_extract()
954{
955	local funcname=f_package_extract
956	local device="$1" name="$2" depended="$3"
957	local devname=
958
959	f_musthavepkg_init # Make sure we have a usable pkg(8) with $PKG_ABI
960
961	$device get name devname
962	f_dprintf "$funcname: device=[%s] name=[%s] depended=[%s]" \
963	          "$devname" "$name" "$depended"
964
965	# Check to make sure it's not already there
966	local varpkg mark=
967	f_str2varname "$name" varpkg
968	f_getvar _mark_$varpkg mark
969	[ "$mark" = "X" ] && return $SUCCESS
970
971	if ! f_device_init $device; then
972		f_show_msg \
973		    "$msg_unable_to_initialize_media_type_for_package_extract"
974		return $FAILURE
975	fi
976
977	# If necessary, initialize the ldconfig hints
978	[ -f "/var/run/ld-elf.so.hints" ] ||
979		f_quietly ldconfig /usr/lib /usr/lib/compat /usr/local/lib
980
981	# Make a couple paranoid locations for temp
982	# files to live if user specified none
983	local tmpdir
984	f_getvar $VAR_PKG_TMPDIR:-/var/tmp tmpdir
985	f_quietly mkdir -p -m 1777 "$tmpdir"
986
987	local path device_type
988	$device get type device_type
989	case "$name" in
990	*/*) path="$name" ;;
991	*)
992		if [ "$device_type" = "$DEVICE_TYPE_HTTP" ]; then
993			path="$PKG_ABI/latest/All/$name"
994		else
995			path="packages/$PKG_ABI/All/$name"
996		fi
997	esac
998
999	# We have a path, call the device strategy routine to check the file
1000	local pkg_ext found=
1001	for pkg_ext in "" $PACKAGE_EXTENSIONS; do
1002		if f_device_get $device "$path$pkg_ext" $PROBE_EXIST; then
1003			path="$path$pkg_ext"
1004			found=1
1005			break
1006		elif [ "$device_type" = "$DEVICE_TYPE_HTTP" ] &&
1007		     f_device_get $device \
1008			"packages/$PKG_ABI/All/$name$pkg_ext" $PROBE_EXIST
1009		then
1010			# Mirroring physical media over HTTP
1011			path="packages/$PKG_ABI/All/$name$pkg_ext"
1012			found=1
1013			break
1014		fi
1015	done
1016	[ "$found" ] && f_dprintf "$funcname: found path=[%s] dev=[%s]" \
1017	                          "$path" "$devname"
1018
1019	local alert=f_show_msg no_confirm=
1020	f_getvar $VAR_NO_CONFIRM no_confirm
1021	[ "$no_confirm" ] && alert=f_show_info
1022
1023	if [ ! "$found" ]; then
1024		f_dprintf "$funcname: No such %s file on %s device" \
1025	                  "$path" "$devname"
1026		$alert "$msg_unable_to_fetch_package_from_selected_media" \
1027		       "$name"
1028		[ "$no_confirm" ] && sleep 2
1029		return $FAILURE
1030	fi
1031
1032	if [ "$depended" ]; then
1033		f_show_info "$msg_adding_package_as_a_dependency_from_media" \
1034		            "$name" "$devname"
1035	else
1036		f_show_info "$msg_adding_package_from_media" "$name" "$devname"
1037	fi
1038
1039	# Request the package be added via pkg-install(8)
1040	if f_debugging; then
1041		f_eval_catch $funcname pkg \
1042			'pkg -d install -${depended:+A}y "%s"' "$name"
1043	else
1044		f_eval_catch $funcname pkg \
1045			'pkg install -${depended:+A}y "%s"' "$name"
1046	fi
1047	if [ $? -ne $SUCCESS ]; then
1048		$alert "$msg_pkg_install_apparently_did_not_like_the_package" \
1049		       "$name"
1050		[ "$no_confirm" ] && sleep 2
1051	else
1052		f_show_info "$msg_package_was_added_successfully" "$name"
1053		sleep 1
1054	fi
1055
1056	return $SUCCESS
1057}
1058
1059# f_package_delete $name
1060#
1061# Delete package by full $name (lacks archive suffix; e.g., `.tbz').
1062#
1063f_package_delete()
1064{
1065	local funcname=f_package_delete
1066	local name="$1"
1067
1068	if ! { [ "$name" ] || { f_getvar $VAR_PACKAGE name && [ "$name" ]; }; }
1069	then
1070		f_dprintf "packageDelete: %s" \
1071		          "$msg_no_package_name_passed_in_package_variable"
1072		return $FAILURE
1073	fi
1074
1075	f_dprintf "$funcname: name=[%s]" "$name"
1076
1077	[ "$name" ] || return $FAILURE
1078
1079	{ # Verify and initialize device media if-defined
1080		f_media_verify &&
1081		f_device_init device_media &&
1082		f_index_initialize
1083	} || return $FAILURE
1084
1085	# Now we have (indirectly via f_index_read()):
1086	#   CATEGORY_MENU_LIST _categories_{varpkg} _rundeps_{varpkg}
1087	#   PACKAGE_CATEGORIES _npkgs
1088
1089	local varpkg
1090	f_str2varname "$name" varpkg
1091
1092	# Just as-in the user-interface (opposed to scripted-use), only allow
1093	# packages with at least one category to be recognized.
1094	#
1095	local pkgcat=
1096	if ! f_getvar _categories_$varpkg pkgcat || [ ! "$pkgcat" ]; then
1097		# $pkg may be a partial name, search the index (this is slow)
1098		f_index_search PACKAGE_INDEX "$name" name
1099		if [ ! "$name" ]; then
1100			f_show_msg \
1101			    "$msg_sorry_package_was_not_found_in_the_index" \
1102			    "$name"
1103			return $FAILURE
1104		fi
1105		f_str2varname "$name" varpkg
1106	fi
1107
1108	# If invoked through the scripted interface, we likely have not yet
1109	# detected the installed packages -- something we should do only once.
1110	#
1111	if [ ! "$PACKAGES_DETECTED" ]; then
1112		f_dprintf "$funcname: Detecting installed packages"
1113		f_package_detect_installed
1114		export PACKAGES_DETECTED=1 # exported for awk(1) ENVIRON[]
1115	fi
1116	# Now we have: _mark_{varpkg}=X for all installed packages
1117
1118	#
1119	# Return failure if the package is not already installed.
1120	#
1121	local pkgmark=
1122	f_getvar _mark_$varpkg pkgmark
1123	if ! [ "$pkgmark" -a ! "${pkgmark#[XUR]}" ]; then
1124		f_show_msg "$msg_package_not_installed_cannot_delete" "$name"
1125		return $FAILURE
1126	fi
1127
1128	#
1129	# Check for dependencies
1130	#
1131	local pkgsel depc=0 udeps=
1132	for pkgsel in $SELECTED_PACKAGES; do
1133		local mark=
1134		f_str2varname $pkgsel varpkg
1135		debug= f_getvar _mark_$varpkg mark
1136		[ "$mark" -a ! "${mark#[XUR]}" ] || continue
1137		local dep rundeps=
1138		debug= f_getvar _rundeps_$varpkg rundeps
1139		for dep in $rundeps; do
1140			if [ "$dep" = "$name" ]; then
1141				# Maybe this package is marked for deletion too
1142				if [ "$mark" = "U" ]; then
1143					udeps="$udeps $pkgsel"
1144				else
1145					depc=$(( $depc + 1 ))
1146				fi
1147				break
1148			fi
1149		done
1150	done
1151	if [ $depc -gt 0 ]; then
1152		local grammatical_s=
1153		[ $depc -gt 1 ] && grammatical_s=s
1154		f_show_msg \
1155			"$msg_package_is_needed_by_other_installed_packages" \
1156			"$name" "$depc" "$grammatical_s"
1157		return $FAILURE
1158	fi
1159
1160	#
1161	# Chase dependencies that are marked for uninstallation
1162	#
1163	for pkgsel in $udeps; do
1164		f_dprintf "$funcname: Uninstalling dependency %s (%s)" \
1165		          "$pkgsel" "marked for delete"
1166		f_package_delete "$pkgsel"
1167	done
1168
1169	#
1170	# OK to perform the delete (no other packages depend on it)...
1171	#
1172	f_show_info "$msg_uninstalling_package_waiting_for_pkg_delete" "$name"
1173	if f_debugging; then
1174		f_eval_catch $funcname pkg 'pkg -d delete -y "%s"' "$name"
1175	else
1176		f_eval_catch $funcname pkg 'pkg delete -y "%s"' "$name"
1177	fi
1178	if [ $? -ne $SUCCESS ]; then
1179		f_show_msg "$msg_pkg_delete_failed" "$name"
1180		return $FAILURE
1181	else
1182		f_dprintf "$funcname: pkg-delete(8) of %s successful" "$name"
1183		f_str2varname "$name" varpkg
1184		setvar _mark_$varpkg ""
1185	fi
1186}
1187
1188# f_package_reinstall $name
1189#
1190# A simple wrapper to f_package_delete() + f_package_add()
1191#
1192f_package_reinstall()
1193{
1194	f_package_delete "$1" && f_package_add "$1"
1195}
1196
1197############################################################ MAIN
1198
1199f_dprintf "%s: Successfully loaded." packages/packages.subr
1200
1201fi # ! $_PACKAGES_PACKAGES_SUBR
1202