xref: /freebsd/usr.sbin/bsdconfig/share/packages/index.subr (revision f7c32ed617858bcd22f8d1b03199099d50125721)
1if [ ! "$_PACKAGES_INDEX_SUBR" ]; then _PACKAGES_INDEX_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# $FreeBSD$
28#
29############################################################ INCLUDES
30
31BSDCFG_SHARE="/usr/share/bsdconfig"
32. $BSDCFG_SHARE/common.subr || exit 1
33f_dprintf "%s: loading includes..." packages/index.subr
34f_include $BSDCFG_SHARE/device.subr
35f_include $BSDCFG_SHARE/media/common.subr
36f_include $BSDCFG_SHARE/packages/musthavepkg.subr
37f_include $BSDCFG_SHARE/strings.subr
38
39BSDCFG_LIBE="/usr/libexec/bsdconfig"
40f_include_lang $BSDCFG_LIBE/include/messages.subr
41
42############################################################ GLOBALS
43
44PACKAGE_INDEX=
45_INDEX_INITTED=
46
47#
48# Default path to pkg(8) repo-packagesite.sqlite database
49#
50SQLITE_REPO="/var/db/pkg/repo-FreeBSD.sqlite"
51
52#
53# Default path to on-disk cache INDEX file
54#
55PACKAGES_INDEX_CACHEFILE="/var/run/bsdconfig/packages_INDEX.cache"
56
57############################################################ FUNCTIONS
58
59# f_index_initialize [$var_to_set]
60#
61# Read and initialize the global index. Returns success unless media cannot be
62# initialized for any reason (e.g. user cancels media selection dialog or an
63# error occurs). The index is sorted before being loaded into $var_to_set.
64#
65# NOTE: The index is processed with f_index_read() [below] after being loaded.
66#
67f_index_initialize()
68{
69	local __funcname=f_index_initialize
70	local __var_to_set="${1:-PACKAGE_INDEX}"
71
72	[ "$_INDEX_INITTED" ] && return $SUCCESS
73
74	# Got any media?
75	f_media_verify || return $FAILURE
76
77	# Make sure we have a usable pkg(8) with $PKG_ABI
78	f_musthavepkg_init
79
80	# Does it move when you kick it?
81	f_device_init device_media || return $FAILURE
82
83	f_show_info "$msg_attempting_to_update_repository_catalogue"
84
85	#
86	# Generate $PACKAGESITE variable for pkg(8) based on media type
87	#
88	local __type __data __site
89	device_media get type __type
90	device_media get private __data
91	case "$__type" in
92	$DEVICE_TYPE_DIRECTORY)
93		__site="file://$__data/packages/$PKG_ABI" ;;
94	$DEVICE_TYPE_FLOPPY)
95		__site="file://${__data:-$MOUNTPOINT}/packages/$PKG_ABI" ;;
96	$DEVICE_TYPE_FTP)
97		f_getvar $VAR_FTP_PATH __site
98		__site="$__site/packages/$PKG_ABI" ;;
99	$DEVICE_TYPE_HTTP)
100		f_getvar $VAR_HTTP_PATH __site
101		__site="$__site/$PKG_ABI/latest" ;;
102	$DEVICE_TYPE_HTTP_PROXY)
103		f_getvar $VAR_HTTP_PROXY_PATH __site
104		__site="$__site/packages/$PKG_ABI" ;;
105	$DEVICE_TYPE_CDROM)
106		__site="file://$MOUNTPOINT/packages/$PKG_ABI"
107		export REPOS_DIR="$MOUNTPOINT/packages/repos" ;;
108	*) # UFS, DISK, CDROM, USB, DOS, NFS, etc.
109		__site="file://$MOUNTPOINT/packages/$PKG_ABI"
110	esac
111
112	f_dprintf "PACKAGESITE=[%s]" "$__site"
113	if ! f_eval_catch $__funcname pkg \
114		'PACKAGESITE="%s" pkg update' "$__site"
115	then
116		f_show_err "$msg_unable_to_update_pkg_from_selected_media"
117		f_device_shutdown device_media
118		return $FAILURE
119	fi
120
121	#
122	# Try to get contents from validated on-disk cache
123	#
124
125	#
126	# Calculate digest used to determine if the on-disk persistent cache
127	# INDEX (containing this digest on the first line) is valid and can be
128	# used to quickly populate the environment.
129	#
130	local __sqlite_digest
131	if ! __sqlite_digest=$( md5 < "$SQLITE_REPO" 2> /dev/null ); then
132		f_show_err "$msg_no_pkg_database_found"
133		f_device_shutdown device_media
134		return $FAILURE
135	fi
136
137	#
138	# Check to see if the persistent cache INDEX file exists
139	#
140	if [ -f "$PACKAGES_INDEX_CACHEFILE" ]; then
141		#
142		# Attempt to populate the environment with the (soon to be)
143		# validated on-disk cache. If validation fails, fall-back to
144		# generating a fresh cache.
145		#
146		if eval $__var_to_set='$(
147			(	# Get digest as the first word on first line
148				read digest rest_ignored
149
150				#
151				# If the stored digest matches the calculated-
152				# one populate the environment from the on-disk
153				# cache and provide success exit status.
154				#
155				if [ "$digest" = "$__sqlite_digest" ]; then
156					cat
157					exit $SUCCESS
158				else
159					# Otherwise, return the current value
160					eval echo \"\$__var_to_set\"
161					exit $FAILURE
162				fi
163			) < "$PACKAGES_INDEX_CACHEFILE" 2> /dev/null
164		)'; then
165			if ! f_index_read "$__var_to_set"; then
166				f_show_err \
167					"$msg_io_or_format_error_on_index_file"
168				return $FAILURE
169			fi
170			_INDEX_INITTED=1
171			return $SUCCESS
172		fi
173		# Otherwise, fall-thru to create a fresh cache from scratch
174	fi
175
176	#
177	# If we reach this point, we need to generate the data from scratch
178	#
179
180	eval "$__var_to_set"='$( pkg rquery -I | (
181		exec 2<&1; dpv -ko /dev/stderr >&$TERMINAL_STDOUT_PASSTHRU \
182			-b "$DIALOG_BACKTITLE" \
183			-- "$msg_generating_index_from_pkg_database"
184	) | sort )'
185
186	#
187	# Attempt to create the persistent on-disk cache
188	#
189
190	# Create a new temporary file to write to
191	local __tmpfile
192	if f_eval_catch -dk __tmpfile $__funcname mktemp \
193		'mktemp -t "%s"' "$pgm"
194	then
195		# Write the temporary file contents
196		echo "$__sqlite_digest" > "$__tmpfile"
197		debug= f_getvar "$__var_to_set" >> "$__tmpfile"
198
199		# Finally, move the temporary file into place
200		case "$PACKAGES_INDEX_CACHEFILE" in
201		*/*) f_eval_catch -d $__funcname mkdir \
202			'mkdir -p "%s"' "${PACKAGES_INDEX_CACHEFILE%/*}"
203		esac
204		f_eval_catch -d $__funcname mv 'mv -f "%s" "%s"' \
205			"$__tmpfile" "$PACKAGES_INDEX_CACHEFILE"
206	fi
207
208	if ! f_index_read "$__var_to_set"; then
209		f_show_err "$msg_io_or_format_error_on_index_file"
210		return $FAILURE
211	fi
212
213	_INDEX_INITTED=1
214	return $SUCCESS
215}
216
217# f_index_read [$var_to_get]
218#
219# Process the INDEX file (contents contained in $var_to_get) and...
220#
221# 1. create a list ($CATEGORY_MENU_LIST) of categories with package counts
222# 2. For convenience, create $_npkgs holding the total number of all packages
223# 3. extract associative categories for each package into $_categories_$varpkg
224# 4. extract runtime dependencies for each package into $_rundeps_$varpkg
225# 5. extract a [sorted] list of categories into $PACKAGE_CATEGORIES
226# 6. create $_npkgs_$varcat holding the total number of packages in category
227#
228# NOTE: $varpkg is the product of f_str2varname $package varpkg
229# NOTE: $package is the name as it appears in the INDEX (no archive suffix)
230# NOTE: We only show categories for which there are at least one package.
231# NOTE: $varcat is the product of f_str2varname $category varcat
232#
233f_index_read()
234{
235	local var_to_get="${1:-PACKAGE_INDEX}"
236
237	# Export variables required by awk(1) below
238	export msg_no_description_provided
239	export msg_all msg_all_desc
240	export VALID_VARNAME_CHARS
241	export msg_packages
242
243	eval "$( debug= f_getvar "$var_to_get" | awk -F'|' '
244	function _asorti(src, dest)
245	{
246		k = nitems = 0
247
248		# Copy src indices to dest and calculate array length
249		for (i in src) dest[++nitems] = i
250
251		# Sort the array of indices (dest) using insertion sort method
252		for (i = 1; i <= nitems; k = i++)
253		{
254			idx = dest[i]
255			while ((k > 0) && (dest[k] > idx))
256			{
257				dest[k+1] = dest[k]
258				k--
259			}
260			dest[k+1] = idx
261		}
262
263		return nitems
264	}
265	function print_category(category, npkgs, desc)
266	{
267		cat = category
268		# Accent the category if the first page has been
269		# cached (also acting as a visitation indicator)
270		if ( ENVIRON["_index_page_" varcat "_1"] )
271			cat = cat "*"
272		printf "'\''%s'\'' '\''%s " packages "'\'' '\''%s'\''\n",
273		       cat, npkgs, desc
274	}
275	BEGIN {
276		valid_chars = ENVIRON["VALID_VARNAME_CHARS"]
277		default_desc = ENVIRON["msg_no_description_provided"]
278		packages = ENVIRON["msg_packages"]
279		tpkgs = 0
280		prefix = ""
281	}
282	{
283		tpkgs++
284		varpkg = $1
285		gsub("[^" valid_chars "]", "_", varpkg)
286		print "_categories_" varpkg "=\"" $7 "\""
287		split($7, pkg_categories, /[[:space:]]+/)
288		for (pkg_category in pkg_categories)
289			categories[pkg_categories[pkg_category]]++
290		print "_rundeps_" varpkg "=\"" $9 "\""
291	}
292	END {
293		print "_npkgs=" tpkgs # For convenience, total package count
294
295		n = _asorti(categories, categories_sorted)
296
297		# Produce package counts for each category
298		for (i = 1; i <= n; i++)
299		{
300			cat = varcat = categories_sorted[i]
301			npkgs = categories[cat]
302			gsub("[^" valid_chars "]", "_", varcat)
303			print "_npkgs_" varcat "=\"" npkgs "\""
304		}
305
306		# Create menu list and generate list of categories at same time
307		print "CATEGORY_MENU_LIST=\""
308		print_category(ENVIRON["msg_all"], tpkgs,
309		               ENVIRON["msg_all_desc"])
310		category_list = ""
311		for (i = 1; i <= n; i++)
312		{
313			cat = varcat = categories_sorted[i]
314			npkgs = categories[cat]
315			cur_prefix = tolower(substr(cat, 1, 1))
316			if ( prefix != cur_prefix )
317				prefix = cur_prefix
318			else
319				cat = " " cat
320			gsub("[^" valid_chars "]", "_", varcat)
321			desc = ENVIRON["_category_" varcat]
322			if ( ! desc ) desc = default_desc
323			print_category(cat, npkgs, desc)
324			category_list = category_list " " cat
325		}
326		print "\""
327
328		# Produce the list of categories (calculated in above block)
329		sub(/^ /, "", category_list)
330		print "PACKAGE_CATEGORIES=\"" category_list "\""
331
332	}' | ( exec 2<&1; dpv -ko /dev/stderr >&$TERMINAL_STDOUT_PASSTHRU \
333		-b "$DIALOG_BACKTITLE" -- "$msg_reading_package_index_data"
334	) )" # End-Quote
335}
336
337# f_index_extract_pages $var_to_get $var_basename $pagesize [$category]
338#
339# Extracts the package INDEX ($PACKAGE_INDEX by default if/when $var_to_get is
340# NULL; but should not be missing) into a series of sequential variables
341# corresponding to "pages" containing up to $pagesize packages. The package
342# INDEX data must be contained in the variable $var_to_get. The extracted pages
343# are stored in variables ${var_basename}_# -- where "#" is a the page number.
344# If $category is set, only packages for that category are extracted.
345# Otherwise, if $category is "All", missing, or NULL, all packages are
346# extracted and no filtering is done.
347#
348f_index_extract_pages()
349{
350	local var_to_get="${1:-PACKAGE_INDEX}" var_basename="$2" pagesize="$3"
351	local category="$4" # Optional
352
353	eval "$(
354		debug= f_getvar "$var_to_get" | awk -F'|' \
355			-v cat="$category" \
356			-v pagesize="$pagesize" \
357			-v var_basename="$var_basename" \
358			-v i18n_all="$msg_all" '
359		BEGIN { n = page = 0 }
360		/'\''/{ gsub(/'\''/, "'\''\\'\'\''") }
361		{
362			if ( cat !~ "(^$|^" i18n_all "$)" && $7 !~ \
363			     "(^|[[:space:]])" cat "([[:space:]]|$)" ) next
364			starting_new_page = (n++ == (pagesize * page))
365			if ( starting_new_page )
366				printf "%s%s", ( n > 1 ? "'\''\n" : "" ),
367				       var_basename "_" ++page "='\''"
368			printf "%s%s", ( starting_new_page ? "" : "\n" ), $0
369		}
370		END { if ( n > 0 ) print "'\''" }'
371	)"
372}
373
374# f_index_search $var_to_get $name [$var_to_set]
375#
376# Search the package INDEX ($PACKAGE_INDEX by default if/when $var_to_get is
377# NULL; but should not be missing) for $name, returning the first match.
378# Matches are strict (not regular expressions) and must match the beginning
379# portion of the package name to be considered a match. If $var_to_set is
380# missing or NULL, output is sent to standard output. If a match is found,
381# returns success; otherwise failure.
382#
383f_index_search()
384{
385	local __var_to_get="${1:-PACKAGE_INDEX}" __pkg_basename="$2"
386	local __var_to_set="$3"
387
388	f_dprintf "f_index_search: Searching package data (in %s) for %s" \
389	          "$__var_to_get" "$__pkg_basename"
390
391	local __pkg=
392	__pkg=$( debug= f_getvar "$__var_to_get" |
393			awk -F'|' -v basename="$__pkg_basename" '
394		BEGIN { n = length(basename) }
395		substr($1, 0, n) == basename { print $1; exit }
396	' )
397	if [ ! "$__pkg" ]; then
398		f_dprintf "f_index_search: No packages matching %s found" \
399		          "$__pkg_basename"
400		return $FAILURE
401	fi
402
403	f_dprintf "f_index_search: Found package %s" "$__pkg"
404	if [ "$__var_to_set" ]; then
405		setvar "$__var_to_set" "$__pkg"
406	else
407		echo "$__pkg"
408	fi
409	return $SUCCESS
410}
411
412############################################################ MAIN
413
414f_dprintf "%s: Successfully loaded." packages/index.subr
415
416fi # ! $_PACKAGES_INDEX_SUBR
417