xref: /freebsd/usr.sbin/bsdconfig/share/packages/index.subr (revision 6d3c0798ccbe7f6d3b677eed31206efc1227be50)
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#
28############################################################ INCLUDES
29
30BSDCFG_SHARE="/usr/share/bsdconfig"
31. $BSDCFG_SHARE/common.subr || exit 1
32f_dprintf "%s: loading includes..." packages/index.subr
33f_include $BSDCFG_SHARE/device.subr
34f_include $BSDCFG_SHARE/media/common.subr
35f_include $BSDCFG_SHARE/packages/musthavepkg.subr
36f_include $BSDCFG_SHARE/strings.subr
37
38BSDCFG_LIBE="/usr/libexec/bsdconfig"
39f_include_lang $BSDCFG_LIBE/include/messages.subr
40
41############################################################ GLOBALS
42
43PACKAGE_INDEX=
44_INDEX_INITTED=
45
46#
47# Default path to pkg(8) repo-packagesite.sqlite database
48#
49SQLITE_REPO="/var/db/pkg/repo-FreeBSD.sqlite"
50
51#
52# Default path to on-disk cache INDEX file
53#
54PACKAGES_INDEX_CACHEFILE="/var/run/bsdconfig/packages_INDEX.cache"
55
56############################################################ FUNCTIONS
57
58# f_index_initialize [$var_to_set]
59#
60# Read and initialize the global index. Returns success unless media cannot be
61# initialized for any reason (e.g. user cancels media selection dialog or an
62# error occurs). The index is sorted before being loaded into $var_to_set.
63#
64# NOTE: The index is processed with f_index_read() [below] after being loaded.
65#
66f_index_initialize()
67{
68	local __funcname=f_index_initialize
69	local __var_to_set="${1:-PACKAGE_INDEX}"
70
71	[ "$_INDEX_INITTED" ] && return $SUCCESS
72
73	# Got any media?
74	f_media_verify || return $FAILURE
75
76	# Make sure we have a usable pkg(8) with $PKG_ABI
77	f_musthavepkg_init
78
79	# Does it move when you kick it?
80	f_device_init device_media || return $FAILURE
81
82	f_show_info "$msg_attempting_to_update_repository_catalogue"
83
84	#
85	# Generate $PACKAGESITE variable for pkg(8) based on media type
86	#
87	local __type __data __site
88	device_media get type __type
89	device_media get private __data
90	case "$__type" in
91	$DEVICE_TYPE_DIRECTORY)
92		__site="file://$__data/packages/$PKG_ABI" ;;
93	$DEVICE_TYPE_HTTP)
94		f_getvar $VAR_HTTP_PATH __site
95		__site="$__site/$PKG_ABI/latest" ;;
96	$DEVICE_TYPE_HTTP_PROXY)
97		f_getvar $VAR_HTTP_PROXY_PATH __site
98		__site="$__site/packages/$PKG_ABI" ;;
99	$DEVICE_TYPE_CDROM)
100		__site="file://$MOUNTPOINT/packages/$PKG_ABI"
101		export REPOS_DIR="$MOUNTPOINT/packages/repos" ;;
102	*) # UFS, DISK, CDROM, USB, DOS, NFS, etc.
103		__site="file://$MOUNTPOINT/packages/$PKG_ABI"
104	esac
105
106	f_dprintf "PACKAGESITE=[%s]" "$__site"
107	if ! f_eval_catch $__funcname pkg \
108		'PACKAGESITE="%s" pkg update' "$__site"
109	then
110		f_show_err "$msg_unable_to_update_pkg_from_selected_media"
111		f_device_shutdown device_media
112		return $FAILURE
113	fi
114
115	#
116	# Try to get contents from validated on-disk cache
117	#
118
119	#
120	# Calculate digest used to determine if the on-disk persistent cache
121	# INDEX (containing this digest on the first line) is valid and can be
122	# used to quickly populate the environment.
123	#
124	local __sqlite_digest
125	if ! __sqlite_digest=$( md5 < "$SQLITE_REPO" 2> /dev/null ); then
126		f_show_err "$msg_no_pkg_database_found"
127		f_device_shutdown device_media
128		return $FAILURE
129	fi
130
131	#
132	# Check to see if the persistent cache INDEX file exists
133	#
134	if [ -f "$PACKAGES_INDEX_CACHEFILE" ]; then
135		#
136		# Attempt to populate the environment with the (soon to be)
137		# validated on-disk cache. If validation fails, fall-back to
138		# generating a fresh cache.
139		#
140		if eval $__var_to_set='$(
141			(	# Get digest as the first word on first line
142				read digest rest_ignored
143
144				#
145				# If the stored digest matches the calculated-
146				# one populate the environment from the on-disk
147				# cache and provide success exit status.
148				#
149				if [ "$digest" = "#$__sqlite_digest" ]; then
150					cat
151					exit $SUCCESS
152				else
153					# Otherwise, return the current value
154					eval echo \"\$__var_to_set\"
155					exit $FAILURE
156				fi
157			) < "$PACKAGES_INDEX_CACHEFILE" 2> /dev/null
158		)'; then
159			if ! f_index_read "$__var_to_set"; then
160				f_show_err \
161					"$msg_io_or_format_error_on_index_file"
162				return $FAILURE
163			fi
164			_INDEX_INITTED=1
165			return $SUCCESS
166		fi
167		# Otherwise, fall-thru to create a fresh cache from scratch
168	fi
169
170	#
171	# If we reach this point, we need to generate the data from scratch
172	#
173
174	# Create a new temporary file to write to
175	local __tmpfile
176	if f_eval_catch -dk __tmpfile $__funcname mktemp \
177		'mktemp -t "%s"' "$pgm"; then
178		local _npkg
179		# Write the temporary file contents
180		echo "#$__sqlite_digest" > "$__tmpfile"
181		f_eval_catch -k _npkg $__funcname pkg \
182			"pkg stat -r | awk '%s'" '/Packages available/ { print $3 }'
183		pkg rquery -I | awk -v npkg=$_npkg \
184			-v msg="$msg_generating_index_from_pkg_database" \
185			-v tmpfile="$__tmpfile" \
186			-v valid_chars="$VALID_VARNAME_CHARS" \
187			-v default_desc="$msg_no_description_provided" \
188			-v packages="$msg_packages" \
189			-v msg_all="$msg_all" \
190			-v msg_all_desc="$msg_all_desc" \
191			-F "|" \
192			-f $BSDCFG_SHARE/packages/index.awk | \
193			$DIALOG --backtitle "$DIALOG_BACKTITLE" \
194			--gauge "$msg_generating_index_from_pkg_database" 0 0
195
196		# Finally, move the temporary file into place
197		case "$PACKAGES_INDEX_CACHEFILE" in
198		*/*) f_eval_catch -d $__funcname mkdir \
199			'mkdir -p "%s"' "${PACKAGES_INDEX_CACHEFILE%/*}"
200		esac
201		f_eval_catch -d $__funcname mv 'mv -f "%s" "%s"' \
202			"$__tmpfile" "$PACKAGES_INDEX_CACHEFILE"
203	else
204		return $FAILURE
205	fi
206
207	if ! f_index_read "$__var_to_set"; then
208		f_show_err \
209			"$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	. $PACKAGES_INDEX_CACHEFILE
244}
245
246# f_index_extract_pages $var_to_get $var_basename $pagesize [$category]
247#
248# Extracts the package INDEX ($PACKAGE_INDEX by default if/when $var_to_get is
249# NULL; but should not be missing) into a series of sequential variables
250# corresponding to "pages" containing up to $pagesize packages. The package
251# INDEX data must be contained in the variable $var_to_get. The extracted pages
252# are stored in variables ${var_basename}_# -- where "#" is a the page number.
253# If $category is set, only packages for that category are extracted.
254# Otherwise, if $category is "All", missing, or NULL, all packages are
255# extracted and no filtering is done.
256#
257f_index_extract_pages()
258{
259	local var_to_get="${1:-PACKAGE_INDEX}" var_basename="$2" pagesize="$3"
260
261	eval "$(
262		debug= f_getvar "$var_to_get" | awk -F'|' \
263			-v pagesize="$pagesize" \
264			-v var_basename="$var_basename" ' \
265		BEGIN { n = page = 0 }
266		/'\''/{ gsub(/'\''/, "'\''\\'\'\''") }
267		{
268			starting_new_page = (n++ == (pagesize * page))
269			if ( starting_new_page )
270				printf "%s%s", ( n > 1 ? "'\''\n" : "" ),
271				       var_basename "_" ++page "='\''"
272			printf "%s%s", ( starting_new_page ? "" : "\n" ), $0
273		}
274		END { if ( n > 0 ) print "'\''" }'
275	)"
276}
277
278# f_index_search $var_to_get $name [$var_to_set]
279#
280# Search the package INDEX ($PACKAGE_INDEX by default if/when $var_to_get is
281# NULL; but should not be missing) for $name, returning the first match.
282# Matches are strict (not regular expressions) and must match the beginning
283# portion of the package name to be considered a match. If $var_to_set is
284# missing or NULL, output is sent to standard output. If a match is found,
285# returns success; otherwise failure.
286#
287f_index_search()
288{
289	local __var_to_get="${1:-PACKAGE_INDEX}" __pkg_basename="$2"
290	local __var_to_set="$3"
291
292	f_dprintf "f_index_search: Searching package data (in %s) for %s" \
293	          "$__var_to_get" "$__pkg_basename"
294
295	local __pkg=
296	__pkg=$( debug= f_getvar "$__var_to_get" |
297			awk -F'|' -v basename="$__pkg_basename" '
298		BEGIN { n = length(basename) }
299		substr($1, 0, n) == basename { print $1; exit }
300	' )
301	if [ ! "$__pkg" ]; then
302		f_dprintf "f_index_search: No packages matching %s found" \
303		          "$__pkg_basename"
304		return $FAILURE
305	fi
306
307	f_dprintf "f_index_search: Found package %s" "$__pkg"
308	if [ "$__var_to_set" ]; then
309		setvar "$__var_to_set" "$__pkg"
310	else
311		echo "$__pkg"
312	fi
313	return $SUCCESS
314}
315
316############################################################ MAIN
317
318f_dprintf "%s: Successfully loaded." packages/index.subr
319
320fi # ! $_PACKAGES_INDEX_SUBR
321