code:
This is qi.info, produced by makeinfo version 6.5 from qi-header.texi.

INFO-DIR-SECTION Package management
START-INFO-DIR-ENTRY
* Qi: (qi).                   A user-friendly package manager.
END-INFO-DIR-ENTRY

File: qi.info,  Node: Top,  Next: Introduction to Qi,  Up: (dir)

Qi user guide
*************

This user guide is for Qi (version 2.9, 22 Jun 2022).

* Menu:

* Introduction to Qi::        Description and features of qi
* Invoking qi::               Command-line options
* The qirc file::             Configuration file
* Packages::                  Managing packages
* Recipes::                   Building packages
* Order files::               Handling build order
* Creating packages::         Making Qi packages
* Examining packages::        Debugging purposes
* Qi exit status::            Exit codes
* Index::

   Copyright � 2019-2022 Matias Andres Fonzo, Santiago del Estero,
Argentina.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

File: qi.info,  Node: Introduction to Qi,  Next: Invoking qi,  Prev: Top,  Up: Top

1 Introduction to Qi
********************

Qi is a simple but well-integrated package manager.  It can create,
install, remove, and upgrade software packages.  Qi produces binary
packages using recipes, which are files containing specific instructions
to build each package from source.  Qi can manage multiple packages
under a single directory hierarchy.  This method allows to maintain a
set of packages and multiple versions of them.  This means that Qi could
be used as the main package manager or complement the existing one.

   Qi offers a friendly command line interface, a global configuration
file, a simple recipe layout to deploy software packages; also works
with binary packages in parallel, speeding up installations and packages
in production.  The format used for packages is a simplified and safer
variant of POSIX pax archive compressed in lzip format.

   Qi is a modern (POSIX-compliant) shell script released under the
terms of the GNU General Public License.  There are only two major
dependencies for the magic: graft(1) and tarlz(1), the rest is expected
to be found in any Unix-like system.

File: qi.info,  Node: Invoking qi,  Next: The qirc file,  Prev: Introduction to Qi,  Up: Top

2 Invoking qi
*************

This chapter describes the synopsis for invoking Qi.

     Usage: qi COMMAND [OPTION...] [FILE]...

One mandatory command specifies the operation that 'qi' should perform,
options are meant to detail how this operation should be performed
during or after the process.

Qi supports the following commands:

'warn'
     Warn about files that will be installed.

'install'
     Install packages.

'remove'
     Remove packages.

'upgrade'
     Upgrade packages.

'extract'
     Extract packages for debugging purposes.

'create'
     Create a .tlz package from directory.

'build'
     Build packages using recipe names.

'order'
     Resolve build order through .order files

Options when installing, removing, or upgrading software packages:

'-f'
'--force'
     Force upgrade of pre-existing packages.

'-k'
'--keep'
     Keep directories when build/remove/upgrade.

     Keep (don't delete) the package directory when using remove/upgrade
     command.

     This will also try to preserve the directories '${srcdir}' and
     '${destdir}' when using build command.  Its effect is available in
     recipes as '${keep_srcdir}' and '${keep_destdir}'.  See *note
     Special variables: Recipes. for details.

'-p'
'--prune'
     Prune conflicts.

'-P'
'--packagedir=<dir>'
     Set directory for package installations.

'-t'
'--targetdir=<dir>'
     Set target directory for symbolic links.

'-r'
'--rootdir=<dir>'
     Use the fully qualified named directory as the root directory for
     all qi operations.

     Note: the target directory and the package directory will be
     relative to the specified directory, excepting the graft log file.

Options when building software packages using recipes:

'-a'
'--architecture'
     Set architecture name for the package.

'-j'
'--jobs'
     Parallel jobs for the compiler.

     This option sets the variable '${jobs}'.  If not specified, default
     sets to 1.

'-S'
'--skip-questions'
     Skip questions on completed recipes.

'-1'
'--increment'
     Increment release number ('${release}' + 1).

     The effect of this option will be omitted if -no-package is being
     used.

'-n'
'--no-package'
     Do not create a .tlz package.

'-i'
'--install'
     Install package after the build.

'-u'
'--upgrade'
     Upgrade package after the build.

'-o'
'--outdir=<dir>'
     Where the packages produced will be written.

     This option sets the variable '${outdir}'.

'-w'
'--worktree=<dir>'
     Where archives, patches, recipes are expected.

     This option sets the variable '${worktree}'.

'-s'
'--sourcedir=<dir>'
     Where compressed sources will be found.

     This option sets the variable '${tardir}'.

Other options:

'-v'
'--verbose'
     Be verbose (an extra -v gives more).

     It sets the verbosity level, default sets to 0.

     The value 1 is used for more verbosity while the value 2 is too
     detailed.  Although at the moment it is limited to graft(1)
     verbosity.

'-N'
'--no-rc'
     Do not read the configuration file.

     This will ignore reading the qirc file.

'-L'
'--show-location'
     Print default directory locations and exit.

     This will print the target directory, package directory, working
     tree, the directory for sources, and the output directory for the
     packages produced.

'-h'
'--help'
     Display the usage and exit.

'-V'
'--version'

     This will print the (short) version information and then exit.

     The same can be achieved if Qi is invoked as 'qi version'.

   When FILE is -, qi can read from the standard input.  See examples
from the *note Packages:: section.

   Exit status: 0 for a normal exit, 1 for minor common errors (help
usage, support not available, etc), 2 to indicate a command execution
error; 3 for integrity check error on compressed files, 4 for empty, not
regular, or expected files, 5 for empty or not defined variables, 6 when
a package already exist, 10 for network manager errors.  For more
details, see the *note Qi exit status:: section.

File: qi.info,  Node: The qirc file,  Next: Packages,  Prev: Invoking qi,  Up: Top

3 The qirc file
***************

The global 'qirc' file offers a way to define variables and tools (such
as a download manager) for default use.  This file is used by qi at
runtime, e.g., to build, install, remove or upgrade packages.

   Variables and their possible values must be declared as any other
variable in the shell.

The command line options related to the package directory and target
directory and some of the command line options used for the build
command, have the power to override the values declared on 'qirc'.  See
*note Invoking qi::.

The order in which qi looks for this file is:

  1. '${HOME}/.qirc' Effective user.

  2. '${sysconfdir}/qirc' System-wide.

   If you intend to run qi as effective user, the file
'${sysconfdir}/qirc' could be copied to '${HOME}/.qirc' setting the
paths for '${packagedir}' and '${targetdir}' according to the '$HOME'.

File: qi.info,  Node: Packages,  Next: Recipes,  Prev: The qirc file,  Up: Top

4 Packages
**********

A package is a suite of programs usually distributed in binary form
which may also contain manual pages, documentation, or any other file
associated to a specific software.

   The package format used by qi is a simplified POSIX pax archive
compressed using lzip(1).  The file extension for packages ends in
'.tlz'.

Both package installation and package de-installation are managed using
two important (internal) variables: '${packagedir}' and '${targetdir}',
these values can be changed in the configuration file or via options.

   '${packagedir}' is a common directory tree where the package contents
will be decompressed (will reside).

   '${targetdir}' is a target directory where the links will be made by
graft(1) taking '${packagedir}/package_name' into account.

Packages are installed in self-contained directory trees and symbolic
links from a common area are made to the package files.  This allows
multiple versions of the same package to coexist on the same system.

4.1 Package conflicts
=====================

All the links to install or remove a package are handled by graft(1).
Since multiple packages can be installed or removed at the same time,
certain conflicts may arise between the packages.

graft(2) defines a CONFLICT as one of the following conditions:

   * If the package object is a directory and the target object exists
     but is not a directory.

   * If the package object is not a directory and the target object
     exists and is not a symbolic link.

   * If the package object is not a directory and the target object
     exists and is a symbolic link to something other than the package
     object.

The default behavior of qi for an incoming package is to ABORT if a
conflict arises.  When a package is going to be deleted, qi tells to
graft(1) to remove those parts that are not in conflict, leaving the
links to the belonging package.  This behavior can be forced if the
-prune option is given.

4.2 Installing packages
=======================

To install a single package, simply type:

     qi install coreutils_8.30_i586-1@tools.tlz

To install multiple packages at once, type:

     qi install gcc_8.3.0_i586-1@devel.tlz rafaela_2.2_i586-1@legacy.tlz ...

Warn about the files that will be linked:

     qi warn bash_5.0_i586-1@shells.tlz

   This is to verify the content of a package before installing it.

See the process of an installation:

     qi install --verbose mariana_3.0_i586-1@woman.tlz

   A second -verbose or -v option gives more (very verbose).

Installing package in a different location:

     qi install --rootdir=/media/floppy lzip_1.21_i586-1@compressors.tlz

   Important: the -rootdir option assumes '${targetdir}' and
'${packagedir}'.  See the following example:

     qi install --rootdir=/home/selk lzip_1.21_i586-1@compressors.tlz

   The content of "lzip_1.21_i586-1@compressors.tlz" will be
decompressed into '/home/selk/pkgs/lzip_1.21_i586-1@compressors'.
Assuming that the main binary for lzip is under
'/home/selk/pkgs/lzip_1.21_i586-1@compressors/usr/bin/' the target for
"usr/bin" will be created at '/home/selk'.  Considering that you have
exported the 'PATH' as '${HOME}/usr/bin', now the system is able to see
the recent lzip command.

Installing from a list of packages using standard input:

     qi install - < PACKAGELIST.txt

   Or in combination with another tool:
     sort -u PACKAGELIST.txt | qi install -

   The sort command will read and sorts the list of declared packages,
while trying to have unique entries for each statement.  The output
produced is captured by Qi to install each package.

   An example of a list containing package names is:
     /var/cache/qi/packages/amd64/tcl_8.6.9_amd64-1@devel.tlz
     /var/cache/qi/packages/amd64/tk_8.6.9.1_amd64-1@devel.tlz
     /var/cache/qi/packages/amd64/vala_0.42.3_amd64-1@devel.tlz

4.3 Removing packages
=====================

To remove a package, simply type:

     qi remove xz_5.2.4_i586-1@compressors.tlz

Remove command will match the package name using '${packagedir}' as
prefix.  For example, if the value of '${packagedir}' has been set to
/usr/pkg, this will be equal to:

     qi remove /usr/pkg/xz_5.2.4_i586-1@compressors

Detailed output:

     qi remove --verbose /usr/pkg/xz_5.2.4_i586-1@compressors

   A second -verbose or -v option gives more (very verbose).

By default the remove command does not preserve a package directory
after removing its links from '${targetdir}', but this behavior can be
changed if the -keep option is passed:

     qi remove --keep /usr/pkg/lzip_1.21_i586-1@compressors

   This means that the links to the package can be reactivated, later:

     cd /usr/pkg && graft -i lzip_1.21_i586-1@compressors

Removing package from a different location:

     qi remove --rootdir=/home/cthulhu xz_5.2.4_i586-1@compressors

Removing a package using standard input:

     echo vala_0.42.3_amd64-1@devel | qi remove -

   This will match with the package directory.

4.4 Upgrading packages
======================

The upgrade command inherits the properties of the installation and
removal process.  To make sure that a package is updated, the package is
installed in a temporary directory taking '${packagedir}' into account.
Once the incoming package is pre-installed, qi can proceed to search and
delete packages that have the same name (considered as previous ones).
Finally, the package is re-installed at its final location and the
temporary directory is removed.

   Since updating a package can be crucial and so to perform a
successful upgrade, from start to finish, you will want to ignore some
important system signals during the upgrade process, those signals are
SIGHUP, SIGINT, SIGQUIT, SIGABRT, and SIGTERM.

To upgrade a package, just type:

     qi upgrade gcc_9.0.1_i586-1@devel.tlz

   This will proceed to upgrade "gcc_9.0.1_i586-1@devel" removing any
other version of "gcc" (if any).

If you want to keep the package directories of versions found during the
upgrade process, just pass:

     qi upgrade --keep gcc_9.0.1_i586-1@devel.tlz

To see the upgrade process:

     qi upgrade --verbose gcc_9.0.1_i586-1@devel.tlz

   A second -verbose or -v option gives more (very verbose).

To force the upgrade of an existing package:

     qi upgrade --force gcc_9.0.1_i586-1@devel.tlz

4.4.1 Package blacklist
-----------------------

To implement general package facilities, either to install, remove or
maintain the hierarchy of packages in a clean manner, qi makes use of
the pruning operation via graft(1) by default:

   There is a risk if those are crucial packages for the proper
functioning of the system, because it implies the deactivation of
symbolic from the target directory, _especially_ when transitioning an
incoming package into its final location during an upgrade.

A blacklist of package names has been devised for the case where a user
decides to upgrade all the packages in the system, or just the crucial
ones, such as the C library.

   The blacklist is related to the upgrade command only, consists in
installing a package instead of updating it or removing previous
versions of it; the content of the package will be updated over the
existing content at '${packagedir}', while the existing links from
'${targetdir}' will be preserved.  A pruning of links will be carried
out in order to re-link possible differences with the recent content,
this helps to avoid leaving dead links in the target directory.

Package names for the blacklist to be declared must be set from the
configuration file.  By default, it is declared using the package name,
which is more than enough for critical system packages, but if you want
to be more specific, you can declare a package using:
'${pkgname}_${pkgversion}_${arch}-${release}' where the package category
is avoided for common matching.  See *note Special variables: Recipes.
for a description of these variables.

   ---------- Footnotes ----------

   (1) For more details about tarlz and the lzip format, visit
<https://lzip.nongnu.org/tarlz.html>.

   (2) The official guide for Graft can be found at
<https://peters.gormand.com.au/Home/tools/graft/graft.html>.

File: qi.info,  Node: Recipes,  Next: Order files,  Prev: Packages,  Up: Top

5 Recipes
*********

A recipe is a file telling qi what to do.  Most often, the recipe tells
qi how to build a binary package from a source tarball.

   A recipe has two parts: a list of variable definitions and a list of
sections.  By convention, the syntax of a section is:

     section_name()
     {
         section lines
     }

   The section name is followed by parentheses, one newline and an
opening brace.  The line finishing the section contains just a closing
brace.  The section names or the function names currently recognized are
'build'.

   The 'build' section (or *shell function*) is an augmented shell
script that contains the main instructions to build software from
source.

   If there are other functions defined by the packager, Qi detects them
for later execution.

5.1 Variables
=============

A "variable" is a *shell variable* defined either in 'qirc' or in a
recipe to represent a string of text, called the variable's "value".
These values are substituted by explicit request in the definitions of
other variables or in calls to external commands.

   Variables can represent lists of file names, options to pass to
compilers, programs to run, directories to look in for source files,
directories to write output to, or anything else you can imagine.

   Definitions of variables in qi have four levels of precedence.
Options which define variables from the command-line override those
specified in the 'qirc' file, while variables defined in the recipe
override those specified in 'qirc', taking priority over those variables
set by command-line options.  Finally, the variables have default values
if they are not defined anywhere.

   Options that set variables through the command-line can only
reference variables defined in 'qirc' and variables with default values.

   Definitions of variables in 'qirc' can only reference variables
previously defined in 'qirc' and variables with default values.

   Definitions of variables in the recipe can only reference variables
set by the command-line, variables previously defined in the recipe,
variables defined in 'qirc', and variables with default values.

5.2 Special variables
=====================

There are variables which can only be set using the command line options
or via 'qirc', there are other special variables which can be defined or
redefined in a recipe.  See the following definitions:

   'outdir' is the directory where the packages produced are written.
This variable can be redefined per-recipe.  Default sets to
'/var/cache/qi/packages'.

   'worktree' is the working tree where archives, patches, and recipes
are expected.  This variable can not be redefined in the recipe.
Default sets to '/usr/src/qi'.

   'tardir' is defined in the recipe to the directory where the tarball
containing the source can be found.  The full name of the tarball is
composed as '${tardir}/$tarname'.  Its value is available in the recipe
as '${tardir}'; a value of .  for 'tardir' sets it to the value of CWD
(Current Working Directory), this is where the recipe lives.

   'arch' is the architecture to compose the package name.  Its value is
available in the recipe as '${arch}'.  Default value is the one that was
set in the Qi configuration.

   'jobs' is the number of parallel jobs to pass to the compiler.  Its
value is available in the recipe as '${jobs}'.  The default value is 1.

   The two variables '${srcdir}' and '${destdir}' can be set in the
recipe, as any other variable, but if they are not, qi uses default
values for them when building a package.

   'srcdir' contains the source code to be compiled, and defaults to
'${program}-${version}'.  'destdir' is the place where the built package
will be installed, and defaults to '${TMPDIR}/package-${program}'.

   If 'pkgname' is left undefined, the special variable 'program' is
assigned by default.  If 'pkgversion' is left undefined, the special
variable 'version' is assigned by default.

   'pkgname' and 'pkgversion' along with: 'version', 'arch', 'release',
and (optionally) 'pkgcategory' are used to produce the package name in
the form:
'${pkgname}_${pkgversion}_${arch}-${release}[@${pkgcategory}].tlz'

   'pkgcategory' is an optional special variable that can be defined on
the recipe to categorize the package name.  If it is defined, then the
package output will be composed as
'${pkgname}_${pkgversion}_${arch}-${release}[@${pkgcategory}.tlz'.
Automatically, the value of 'pkgcategory' will be prefixed using the '@'
(at) symbol which will be added to the last part of the package name.

   A special variable called 'replace' can be used to declare package
names that will be replaced at installation time.

   The special variables 'keep_srcdir' and 'keep_destdir' are provided
in order to preserve the directories '${srcdir}' or '${destdir}', if
those exists as such.  Note: The declaration of these variables are
subject to manual deactivation; its purpose in recipes is to preserve
the directories that relate to the package's build (source) and
destination directory, that is so that another recipe can get a new
package (or meta package) from there.  For example, the declarations can
be done as:

     keep_srcdir=keep_srcdir
     keep_destdir=keep_destdir

   Then from another recipe you would proceed to copy the necessary
files that will compose the meta package, from the main function you
must deactivate the variables at the end:

     unset -v keep_srcdir keep_destdir

   This will leave the 'keep_srcdir' and 'keep_destdir' variables blank
to continue with the rest of the recipes.

   The variable 'tarlz_compression_options' can be used to change the
default compression options in tarlz(1), default sets to '-9 --solid'.
For example if the variable is declared as:

     tarlz_compression_options="-0 --bsolid"

   It will change the granularity of tarlz(1) by using the '--bsolid'
option (1), as well as increasing the compression speed by lowering the
compression level with '-0'.

   This is only recommended for recipes where testing, or faster
processing is desired to create the packaged file more quickly.  It is
not recommended for production or general distribution of binary
packages.

A typical recipe contains the following variables:

   * 'program': Software name.

     It matches the source name.  It is also used to compose the name of
     the package if '${pkgname}' is not specified.

   * 'version': Software version.

     It matches the source name.  It is also used to compose the version
     of the package if '${pkgversion}' is not specified.

   * 'arch': Software architecture.

     It is used to compose the architecture of the package in which it
     is build.

   * 'release': Release number.

     This is used to reflect the release number of the package.  It is
     recommended to increase this number after any significant change in
     the recipe or post-install script.

   * 'pkgcategory': Package category.

     Optional but recommended variable to categorize the package name
     when it is created.

Obtaining sources over the network must be declared in the recipe using
the 'fetch' variable.

   The variables 'netget' and 'rsync' can be defined in 'qirc' to
establish a network downloader in order to get the sources.  If they are
not defined, qi uses default values:

   'netget' is the general network downloader tool, defaults sets to
'wget2 -c -w1 -t3 --no-check-certificate'.

   'rsync' is the network tool for sources containing the prefix for the
RSYNC protocol, default sets to 'rsync -v -a -L -z -i --progress'.

   The variable 'description' is used to print the package description
when a package is installed.

   A description has two parts: a brief description, and a long
description.  By convention, the syntax of 'description' is:

     description="
     Brief description.

     Long description.
     "

   The first line of the value represented is a brief description of the
software (called "blurb").  A blank line separates the _brief
description_ from the _long description_, which should contain a more
descriptive description of the software.

An example looks like:

     description="
     The GNU core utilities.

     The GNU core utilities are the basic file, shell and text manipulation
     utilities of the GNU operating system.  These are the core utilities
     which are expected to exist on every operating system.
     "

   Please consider a length limit of 78 characters as maximum, because
the same one would be used on the meta file creation.  See *note The
meta file: Recipes. section.

   The 'homepage' variable is used to declare the main site or home
page:

     homepage=https://www.gnu.org/software/gcc

   The variable 'license' is used for license information(2).  Some code
in the program can be covered by license A, license B, or license C. For
"separate licensing" or "heterogeneous licensing", we suggest using *|*
for a disjunction, *&* for a conjunction (if that ever happens in a
significant way), and comma for heterogeneous licensing.  Comma would
have lower precedence, plus added special terms.

     license="LGPL, GPL | Artistic - added permission"

5.3 Writing recipes
===================

Originally, Qi was designed for the series of Dragora GNU/Linux-Libre 3;
this doesn't mean you can't use it in another distribution, just that if
you do, you'll have to try it out for yourself.  To help with this, here
are some references to well-written recipes:

   * <https://git.savannah.nongnu.org/cgit/dragora.git/tree/recipes>
   * <https://notabug.org/dragora/dragora/src/master/recipes>
   * <https://notabug.org/dragora/dragora-extras/src/master/recipes>
   *
     <https://git.savannah.nongnu.org/cgit/dragora/dragora-extras.git/tree/recipes>

5.4 Building packages
=====================

A recipe is any valid regular file.  Qi sets priorities for reading a
recipe, the order in which qi looks for a recipe is:

  1. Current working directory.

  2. If the specified path name does not contain "recipe" as the last
     component.  Qi will complete it by adding "recipe" to the path
     name.

  3. If the recipe is not in the current working directory, it will be
     searched under '${worktree}/recipes'.  The last component will be
     completed adding "recipe" to the specified path name.

To build a single package, type:

     qi build x-apps/xterm

Multiple jobs can be passed to the compiler to speed up the build
process:

     qi build --jobs 3 x-apps/xterm

Update or install the produced package (if not already installed) when
the build command ends:

     qi build -j3 --upgrade x-apps/xterm

Only process a recipe but do not create the binary package:

     qi build --no-package dict/aspell

   The options -install or -upgrade have no effect when -no-package is
given.

This is useful to inspect the build process of the above recipe:

   qi build -keep -no-package dict/aspell 2>&1 | tee aspell-log.txt

   The -keep option could preserve the source directory and the
destination directory for later inspection.  A log file of the build
process will be created redirecting both, standard error and standard
output to tee(1).

5.5 Variables from the environment
==================================

Qi has environment variables which can be used at build time:

   The variable 'TMPDIR' sets the temporary directory for sources, which
is used for package extractions (see *note Examining packages::) and is
prepended to the value of '${srcdir}' and '${destdir}' in build command.
By convention its default value is equal to '/usr/src/qi/build'.

   The variables 'QICFLAGS', 'QICXXFLAGS', 'QILDFLAGS', and 'QICPPFLAGS'
have no effect by default.  The environment variables such as 'CFLAGS',
'CXXFLAGS', 'LDFLAGS', and 'CPPFLAGS' are unset at compile time:

Recommended practice is to set variables in the command line of
'configure' or _make(1)_ instead of exporting to the environment.  As
follows:

   <https://www.gnu.org/software/make/manual/html_node/Environment.html>
     It is not wise for makefiles to depend for their functioning on
     environment variables set up outside their control, since this
     would cause different users to get different results from the same
     makefile.  This is against the whole purpose of most makefiles.

   Setting environment variables for configure is deprecated because
running configure in varying environments can be dangerous.

   <https://gnu.org/savannah-checkouts/gnu/autoconf/manual/autoconf-2.69/html_node/Defining-Variables.html>
     Variables not defined in a site shell script can be set in the
     environment passed to configure.  However, some packages may run
     configure again during the build, and the customized values of
     these variables may be lost.  In order to avoid this problem, you
     should set them in the configure command line, using 'VAR=value'.
     For example:

     './configure CC=/usr/local2/bin/gcc'

   <https://www.gnu.org/savannah-checkouts/gnu/autoconf/manual/autoconf-2.69/html_node/Setting-Output-Variables.html>
     If for instance the user runs 'CC=bizarre-cc ./configure', then the
     cache, config.h, and many other output files depend upon bizarre-cc
     being the C compiler.  If for some reason the user runs ./configure
     again, or if it is run via './config.status --recheck', (See
     Automatic Remaking, and see config.status Invocation), then the
     configuration can be inconsistent, composed of results depending
     upon two different compilers.  [...]  Indeed, while configure can
     notice the definition of CC in './configure CC=bizarre-cc', it is
     impossible to notice it in 'CC=bizarre-cc ./configure', which,
     unfortunately, is what most users do.  [...]  configure: error:
     changes in the environment can compromise the build.

   If the 'SOURCE_DATE_EPOCH' environment variable is set to a UNIX
timestamp (defined as the number of seconds, excluding leap seconds,
since 01 Jan 1970 00:00:00 UTC.); then the given timestamp will be used
to overwrite any newer timestamps on the package contents (when it is
created).  More information about this can be found at
<https://reproducible-builds.org/specs/source-date-epoch/>.

5.6 The meta file
=================

The "meta file" is a regular file created during the build process, it
contains information about the package such as package name, package
version, architecture, release, fetch address, description, and other
minor data extracted from processed recipes.  The name of the file is
generated as '${full_pkgname}.tlz.txt', and its purpose is to reflect
essential information to the user without having to look inside the
package content.  The file format is also intended to be used by other
scripts or by common Unix tools.

   The content of a meta file looks like:

     #
     # Pattern scanning and processing language.
     #
     # The awk utility interprets a special-purpose programming language
     # that makes it possible to handle simple data-reformatting jobs
     # with just a few lines of code.  It is a free version of 'awk'.
     #
     # GNU awk implements the AWK utility which is part of
     # IEEE Std 1003.1 Shell and Utilities (XCU).
     #

     QICFLAGS="-O2"
     QICXXFLAGS="-O2"
     QILDFLAGS=""
     QICPPFLAGS=""
     pkgname=gawk
     pkgversion=5.0.1
     arch=amd64
     release=1
     pkgcategory="tools"
     full_pkgname=gawk_5.0.1_amd64-1@tools
     blurb="Pattern scanning and processing language."
     homepage="https://www.gnu.org/software/gawk"
     license="GPLv3+"
     fetch="https://ftp.gnu.org/gnu/gawk/gawk-5.0.1.tar.lz"
     replace=""

   A package descriptions is extracted from the variable 'description'
where each line is interpreted literally and pre-formatted to fit in
(exactly) *80 columns*, plus the character '#' and a blank space is
prefixed to every line (shell comments).

In addition to the Special variables, there are implicit variables such
as 'blurb':

   The 'blurb' variable is related to the special variable
'description'.  Its value is made from the first (substantial) line of
'description', mentioned as the "brief description".

   The build flags such as 'QICFLAGS', 'QICXXFLAGS', 'QILDFLAGS', and
'QICPPFLAGS' are only added to the meta file if the declared variable
'arch' is not equal to the "noarch" value.

   ---------- Footnotes ----------

   (1) About the '--bsolid' granularity option of tarlz(1),
<https://www.nongnu.org/lzip/manual/tarlz_manual.html#g_t_002d_002dbsolid>.

   (2) The proposal for 'license' was made by Richard M. Stallman at
<https://lists.gnu.org/archive/html/gnu-linux-libre/2016-05/msg00003.html>.

File: qi.info,  Node: Order files,  Next: Creating packages,  Prev: Recipes,  Up: Top

6 Order files
*************

The order command has the purpose of resolving the build order through
.order files.  An order file contains a list of recipe names, by default
does not perform any action other than to print a resolved list in
descending order.  For example, if *a* depends on *b* and *c*, and *c*
depends on *b* as well, the file might look like:

     a: c b
     b:
     c: b

   Each letter represents a recipe name, complete dependencies for the
first recipe name are listed in descending order, which is printed from
right to left, and removed from left to right:

   OUTPUT

     b
     c
     a

   Blank lines, colons and parentheses are simply ignored.  Comment
lines beginning with '#' are allowed.

An order file could be used to build a series of packages, for example,
if the content is:

     # Image handling libraries

     libs/libjpeg-turbo: devel/nasm
     x-libs/jasper: libs/libjpeg-turbo
     libs/tiff: libs/libjpeg-turbo

   To proceed with each recipe, we can type:

     qi order imglibs.order | qi build --install -

   The output of 'qi order imglibs.order' tells to qi in which order it
should build the recipes:

     devel/nasm
     libs/libjpeg-turbo
     x-libs/jasper
     libs/tiff

File: qi.info,  Node: Creating packages,  Next: Examining packages,  Prev: Order files,  Up: Top

7 Creating packages
*******************

The creation command is an internal function of qi to make new Qi
compatible packages.  A package is produced using the contents of the
Current Working Directory and the package file is written out.

     Usage: qi create [OUTPUT/PACKAGENAME.TLZ]...

   The argument for the file name to be written must contain a fully
qualified named directory as the output directory where the package
produced will be written.  The file name should be composed using the
full name: name-version-architecture-release[@pkgcategory].tlz

   EXAMPLE

     cd /usr/pkg
     cd claws-mail_3.17.1_amd64-1@x-apps
     qi create /var/cache/qi/packages/claws-mail_3.17.1_amd64-1@x-apps

   In this case, the package "claws-mail_3.17.1_amd64-1@x-apps" will be
written into '/var/cache/qi/packages/'.

All packages produced are complemented by a checksum file (.sha256).

File: qi.info,  Node: Examining packages,  Next: Qi exit status,  Prev: Creating packages,  Up: Top

8 Examining packages
********************

The extraction command serves to examine binary packages for debugging
purposes.  It decompresses a package into a single directory, verifying
its integrity and preserving all of its properties (owner and
permissions).

     Usage: qi extract [PACKAGENAME.TLZ]...

   EXAMPLE

     qi extract mksh_R56c_amd64-1@shells.tlz

   This action will put the content of "mksh_R56c_amd64-1@shells.tlz"
into a single directory, this is a private directory for the user who
requested the action, creation operation will be equal to *u=rwx,g=,o=
(0700)*.  The package content will reside on this location, default mask
to deploy the content will be equal to *u=rwx,g=rwx,o=rwx (0000)*.

Note: the creation of the custom directory is influenced by the value of
the 'TMPDIR' variable.

File: qi.info,  Node: Qi exit status,  Next: Index,  Prev: Examining packages,  Up: Top

9 Qi exit status
****************

All the exit codes are described in this chapter.

'0'
     Successful completion (no errors).

'1'
     Minor common errors:

        * Help usage on invalid options or required arguments.

        * Program needed by qi (prerequisite) is not available.

'2'
     Command execution error:

     This code is used to return the evaluation of an external command
     or shell arguments in case of failure.

'3'
     Integrity check error for compressed files.

     Compressed files means:

        * A tarball file from tar(1), typically handled by the GNU tar
          implementation.  Supported extensions: .tar, .tar.gz, .tgz,
          .tar.Z, .tar.bz2, .tbz2, .tbz, .tar.xz, .txz, .tar.zst, .tzst

        * A tarball file from tarlz(1).  Supported extensions: .tar.lz,
          .tlz

        * Zip files from unzip(1).  Supported extensions: .zip, .ZIP

        * Gzip files from gzip(1).  Supported extensions: .gz, .Z

        * Bzip2 files from bzip2(1).  Supported extension: .bz2

        * Lzip files from lzip(1).  Supported extension: .lz

        * Xz files from xz(1).  Supported extension: .xz

        * Zstd files from zstd(1).  Supported extension: .zst

'4'
     File empty, not regular, or expected.

     It's commonly expected:

        * An argument for giving commands.

        * A regular file or readable directory.

        * An expected extension: .tlz, .sha256, .order.

        * A protocol supported by the network downloader tool.

'5'
     Empty or not defined variable:

     This code is used to report empty or undefined variables (usually
     variables coming from a recipe or assigned arrays that are tested).

'6'
     Package already installed:

     The package directory for an incoming .tlz package already exists.

'10'
     Network manager error:

     This code is used if the network downloader tool fails for some
     reason.

File: qi.info,  Node: Index,  Prev: Qi exit status,  Up: Top

Index
*****

[index]
* Menu:

* configuration file:                    The qirc file.       (line   6)
* environment variables:                 Recipes.             (line 298)
* exit codes:                            Qi exit status.      (line   6)
* handling build order:                  Order files.         (line   6)
* introduction to qi:                    Introduction to Qi.  (line   6)
* invocation:                            Invoking qi.         (line   6)
* managing packages:                     Packages.            (line   6)
* package blacklist:                     Packages.            (line 189)
* package build:                         Recipes.             (line 252)
* package conflicts:                     Packages.            (line  31)
* package creation:                      Creating packages.   (line   6)
* package de-installation:               Packages.            (line 112)
* package examination:                   Examining packages.  (line   6)
* package installation:                  Packages.            (line  56)
* package upgrade:                       Packages.            (line 151)
* recipes:                               Recipes.             (line   6)
* special variables:                     Recipes.             (line  61)
* the meta file:                         Recipes.             (line 355)
* variables:                             Recipes.             (line  32)
* writing recipes:                       Recipes.             (line 238)

Tag Table:
Node: Top212
Node: Introduction to Qi1191
Node: Invoking qi2395
Node: The qirc file6523
Node: Packages7487
Ref: Packages-Footnote-115523
Ref: Packages-Footnote-215625
Node: Recipes15739
Ref: Recipes-Footnote-132194
Ref: Recipes-Footnote-232331
Node: Order files32477
Node: Creating packages33798
Node: Examining packages34786
Node: Qi exit status35704
Node: Index37713

End Tag Table

Local Variables:
coding: iso-8859-1
End:


code:
# Build recipe for tarlz.
#
# Copyright (c) 2019-2022 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

program=tarlz
version=0.22
release=2

# Define a category for the output of the package name
pkgcategory=tools

tarname=${program}-${version}.tar.lz

# Remote source(s)
fetch=https://download-mirror.savannah.gnu.org/releases/lzip/tarlz/$tarname

homepage=https://lzip.nongnu.org/tarlz.html
license=GPLv2+

description="
Archiver with multimember lzip compression (version $version).

Tarlz is a combined implementation of the tar archiver and the lzip
compressor. By default tarlz creates, lists and extracts archives in a
simplified posix pax format compressed with lzip on a per file basis.
Each tar member is compressed in its own lzip member, as well as the
end-of-file blocks. This method adds an indexed lzip layer on top of
the tar archive, making it possible to decode the archive safely in
parallel.  The resulting multimember tar.lz archive is fully backward
compatible with standard tar tools like GNU tar, which treat it like
any other tar.lz archive.  Tarlz can append files to the end of such
compressed archives.
"

# Limit package name to the program name
full_pkgname="${program}@${pkgcategory}"

# Source documentation
docs="AUTHORS COPYING ChangeLog NEWS README"
docsdir="${docdir}/${program}"

build()
{
    unpack "${tardir}/$tarname"

    cd "$srcdir"

    # Set sane permissions
    chmod -R u+w,go-w,a+rX-s .

    ./configure CPPFLAGS="$QICPPFLAGS" \
    CXXFLAGS+="$QICXXFLAGS" LDFLAGS="$QILDFLAGS -static" \
     $configure_args \
     --infodir=$infodir \
     --mandir=$mandir \
     --build="$(gcc -dumpmachine)"

    make -j${jobs} V=1
    make -j${jobs} DESTDIR="$destdir" install

    # Compress info documents and manual page

    rm -f "${destdir}/${infodir}/dir";	# Redundancy
    lzip -9 \
     "${destdir}/${infodir}/tarlz.info" \
     "${destdir}/${mandir}/man1/tarlz.1"

    # Copy documentation
    mkdir -p "${destdir}/$docsdir"
    cp -p $docs "${destdir}/$docsdir"
}

repo_name: dustdfg/dragora

license: mit


code:
# Build recipe for which.
#
# Copyright (c) 2018 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

program=which
version=2.21
release=1

# Define a category for the output of the package name
pkgcategory=tools

tarname=${program}-${version}.tar.gz

# Remote source(s)
fetch=https://ftp.gnu.org/gnu/which/$tarname

description="
Shows the full path of (shell) commands.

Which is a utility that prints out the full path of the executables
that the shell would execute when the passed program names would have
been entered on the shell prompt.
"

homepage=https://www.gnu.org/software/which
license=GPLv3+

# Source documentation
docs="AUTHORS COPYING EXAMPLES NEWS README README.alias"
docsdir="${docdir}/${program}-${version}"

build()
{
    unpack "${tardir}/$tarname"

    cd "$srcdir"

    # Set sane permissions
    chmod -R u+w,go-w,a+rX-s .

    ./configure CPPFLAGS="$QICPPFLAGS" CFLAGS="$QICFLAGS" LDFLAGS="$QILDFLAGS -static" \
     $configure_args \
     --infodir=$infodir \
     --mandir=$mandir \
     --build="$(gcc -dumpmachine)"

    make -j${jobs} V=1
    make -j${jobs} DESTDIR="$destdir" install

    # Compress pages and copy documentation

    rm -f "${destdir}/${infodir}/dir"	# Redundancy.
    lzip -9 "${destdir}/${infodir}/which.info" \
            "${destdir}/${mandir}/man1/which.1"

    mkdir -p "${destdir}/$docsdir"
    cp -p $docs "${destdir}/$docsdir"
}


code:
# Build recipe for less.
#
# Copyright (c) 2016-2019, 2021 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

program=less
version=590
release=2

# Define a category for the output of the package name
pkgcategory=tools

tarname=${program}-${version}.tar.gz

# Remote source(s)
fetch=https://ftp.gnu.org/gnu/less/$tarname

description="
A text file viewer.

Less is a pager.  A pager is a program that displays text files.

This package also includes the 'lesspipe.sh' script.
"

homepage=https://www.gnu.org/software/less
license=GPLv3+

# Source documentation
docs="COPYING LICENSE NEWS README"
docsdir="${docdir}/${program}-${version}"

build()
{
    unpack "${tardir}/$tarname"

    cd "$srcdir"

    # Set sane permissions
    chmod -R u+w,go-w,a+rX-s .

    ./configure CPPFLAGS="$QICPPFLAGS" \
    CFLAGS="$QICFLAGS" LDFLAGS="$QILDFLAGS -static" \
     $configure_args \
     --mandir=$mandir \
     --with-regex=pcre2 \
     --with-secure \
     --build="$(gcc -dumpmachine)"

    make -j${jobs} V=1
    make -j${jobs} DESTDIR="$destdir" install

    # Include our custom lesspipe.sh version (which has support for lzip)

    cp -p "${worktree}/archive/less/usr/bin/lesspipe.sh" "${destdir}/usr/bin"
    chmod 755 "${destdir}/usr/bin/lesspipe.sh"

    # Include profile file
    mkdir -p "${destdir}/etc/profile.d"
    cat "${worktree}/archive/less/etc/profile.d/less.sh" \
      > "${destdir}/etc/profile.d/less.sh"

    # To handle config file(s)
    touch "${destdir}/etc/profile.d/.graft-config"

    # Compress and link man pages (if needed)
    if test -d "${destdir}/$mandir"
    then
        (
            cd "${destdir}/$mandir"
            find . -type f -exec lzip -9 {} +
            find . -type l | while read -r file
            do
                ln -sf "$(readlink -- "$file").lz" "${file}.lz"
                rm -- "$file"
            done
        )
    fi

    # Copy documentation
    mkdir -p "${destdir}/$docsdir"
    cp -p $docs "${destdir}/$docsdir"
}


code:
#
# qirc: Runtime configuration file for Qi.
#
# Qi looks for this file in:
#     1 - $HOME/.qirc
#     2 - ${sysconfdir}/qirc
#
# For more information, type: info qi 'the qirc file'
#
# Uncomment a variable to set a new value other than the default.

### FIRST SECTION: package settings

# Package installation directory
#packagedir=@PACKAGEDIR@

# Target directory where the links will be made
#targetdir=@TARGETDIR@

# List of package names to be installed rather than being upgraded.
#
# This is to try to perform an atomic upgrade instead of pruning
# symbolic links through graft(1), which can render your system unusable.
#
# For more details, type: info qi 'package blacklist'
#
#blacklist="perl5 graft tarlz plzip musl glibc coreutils bash mksh"

# Verbosity level
#verbose=0

### SECOND SECTION: build settings

# Temporary directory for sources during compilation
#TMPDIR=/usr/src/qi/build

# C compiler flags (to be used on CFLAGS)
#QICFLAGS="-O2"

# C++ compiler flags (to be used on CXXFLAGS)
#QICXXFLAGS="-O2"

# Flags for the linker (to be used on LDFLAGS)
#QILDFLAGS=""

# C/C++ preprocessor flags (to be used on CPPFLAGS)
#QICPPFLAGS=""

# Time of the last modification to the source code
#SOURCE_DATE_EPOCH=$(date +%s)

# Parallel jobs for the compiler
#jobs=1

# Output directory where the packages are written
#outdir=/var/cache/qi/packages

# Working tree where archives, patches, and recipes are expected
#worktree=/usr/src/qi

# Where to find the sources (tarballs)
#tardir=/usr/src/qi/sources

# General network downloader
#netget="wget2 -c -w1 -t3 --no-check-certificate"

# Network tool for the RSYNC protocol
#rsync="rsync -v -a -L -z -i --progress"

# Default compression options used for tarlz(1)
#tarlz_compression_options="-9 --solid"

# Arguments for 'configure'
configure_args="--prefix=@PREFIX@ --libexecdir=@LIBEXECDIR@ --bindir=@BINDIR@ --sbindir=@SBINDIR@ --sysconfdir=@SYSCONFDIR@ --localstatedir=@LOCALSTATEDIR@"

# Default package architecture
arch=@ARCH@

# Documentation prefixes
infodir=@INFODIR@
mandir=@MANDIR@
docdir=@DOCDIR@


code:
#! /bin/sh -
# Copyright (C) 2016-2022 Matias Fonzo <selk@dragora.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# EXIT STATUS
# 0  = Successful completion
# 1  = Minor common errors (e.g: help usage, support not available)
# 2  = Command execution error
# 3  = Integrity check error for compressed files
# 4  = File empty, not regular, or expected
# 5  = Empty or not defined variable
# 6  = Package already installed
# 10 = Network manager error

PROGRAM="${0##*/}"

LC_ALL=C;	# Override locale settings.
umask 022;	# Remove write permission for group and other.
export LC_ALL

### Functions

usage()
{
    printf '%s' \
"Usage: $PROGRAM COMMAND [OPTIONS] [FILE]...
"'A simple but well-integrated package manager.

List of commands:
  warn                     Warn about files that will be installed
  install                  Install packages
  remove                   Remove packages
  upgrade                  Upgrade packages
  extract                  Extract packages for debugging purposes
  create                   Create a .tlz package from directory
  build                    Build packages using recipe names
  order                    Resolve build order through .order files

Options when installing, removing, or upgrading software packages:
  -f, --force              Force upgrade of pre-existing packages
  -k, --keep               Keep package directory when remove/upgrade
  -p, --prune              Prune conflicts
  -P, --packagedir=<dir>   Set directory for package installations
  -t, --targetdir=<dir>    Set target directory for symbolic links
  -r, --rootdir=<dir>      Use the fully qualified named directory as
                           the root directory for all qi operations
                           Note: the target directory and the package
                           directory will be relative to the specified
                           directory, excepting the graft log file

Options when building software packages using recipes:
  -a, --architecture       Set architecture name for the package
  -j, --jobs               Parallel jobs for the compiler
  -k, --keep               Keep ${srcdir} or ${destdir} when build
  -S, --skip-questions     Skip questions on completed recipes
  -1, --increment          Increment release number (${release} + 1)
  -n, --no-package         Do not create a .tlz package
  -i, --install            Install package after the build
  -u, --upgrade            Upgrade package after the build
  -o, --outdir=<dir>       Where the packages produced will be written
  -w, --worktree=<dir>     Where archives, patches, recipes are expected
  -s, --sourcedir=<dir>    Where compressed sources will be found

Other options:
  -N, --no-rc              Do not read the configuration file
  -v, --verbose            Be verbose (an extra -v gives more)
  -L, --show-location      Print default directory locations and exit
  -h, --help               Display this help and exit
  -V, --version            Output version information and exit

Some influential environment variables:
  TMPDIR                   Temporary directory for sources
  QICFLAGS                 C compiler flags (to be used on CFLAGS)
  QICXXFLAGS               C++ compiler flags (to be used on CXXFLAGS)
  QILDFLAGS                Flags for the linker (to be used on LDFLAGS)
  QICPPFLAGS               C/C++ preprocessor flags (to be used on CPPFLAGS)
  SOURCE_DATE_EPOCH        Last modification time for created packages

When FILE is -, read standard input.

Exit status: 0 for a normal exit, 1 for minor common errors (help usage,
support not available, etc), 2 to indicate a command execution error;
3 for integrity check error on compressed files, 4 for empty, not
regular, or expected files, 5 for empty or not defined variables,
6 when a package already exist, 10 for network manager errors.

Qi home page: https://www.dragora.org
'
}

warn()
{
    printf '%s\n' "$@" 1>&2
}

is_readable()
{
    if test -e "$1"
    then
        if ! test -r "$1"
        then
            echo "${PROGRAM}: cannot read ${1}: Permission denied" 1>&2
            return 1
        fi
    else
        echo "${PROGRAM}: cannot access ${1}: No such file or directory" 1>&2
        return 1
    fi
}

# Portable alternative to the file operator -nt (among shells)
is_newer()
{
    if test -n "$(find "$1" -prune -newer "$2" -print)"
    then
        return 0
    fi
    return 1
}

# Determine whether $2 matches pattern $1
fnmatch()
{
    case $2 in
    $1)
        return 0
        ;;
    *)
        return 1
        ;;
    esac
}

chkstatus_or_exit()
{
    status=$?

    if test $status -ne 0
    then
        echo "^ Return status = $status" 1>&2
        exit "${1-2}";	# If not given, defaults to 2
    fi

    unset -v status
}

readconfig()
{
    if test "${_readconfig:-readconfig}" = readconfig
    then
        if is_readable "$HOME/.qirc" 2> /dev/null
        then
            _rcfile="$HOME/.qirc"
        fi

        echo "Importing configuration file from \`${_rcfile}' ..."
        . "$_rcfile" || chkstatus_or_exit 5
    fi
    unset -v _readconfig
}

### Mode functions

mode_build()
{
    recipe=$1

    echo ""
    echo "{@} Building \"${recipe}\" ..."

    # A recipe is any valid regular file.  Qi sets priorities for reading
    # a recipe, the order in which qi looks for a recipe is:
    #
    # 1. Current working directory.
    #
    # 2. If the specified path name does not contain "recipe" as the last
    # component.  Qi will complete it by adding "recipe" to the path
    # name.
    #
    # 3. If the recipe is not in the current working directory, it will be
    # searched under '${worktree}/recipes'.  The last component will be
    # completed adding "recipe" to the specified path name.

    if test ! -f "$recipe"
    then
        if test -f "${recipe}/recipe"
        then
            recipe="${recipe}/recipe"
        elif test -f "${worktree}/recipes/${recipe}/recipe"
        then
            recipe="${worktree}/recipes/${recipe}/recipe"
        fi
    fi

    test -f "$recipe" || {
        warn "\`${recipe}' is not a regular file."
        exit 4
    }

    # Complain if the file name is not "recipe"

    if test "${recipe##*/}" != recipe
    then
        warn "\`${recipe}' is not a valid recipe name."
        exit 4
    fi

    # Start preparations to import the recipe

    # Get working directory and base name of the recipe

    CWD="$(CDPATH='' cd -P -- "$(dirname -- "$recipe")" && pwd -P)"
    recipe="$(basename -- "$recipe")"

    # Check readability for load the recipe on success

    is_readable "${CWD}/$recipe" || exit 4

    # Create external directories if needed
    for directory in "${worktree}/archive" "${worktree}/patches" "${worktree}/recipes" "$tardir"
    do
        test -d "$directory" || mkdir -p -- "$directory"
    done
    unset -v directory

    # Variables treatment for the current and the next recipe.
    #
    # Unset special variables that can only be predefined in
    # the recipe and does not come from '${sysconfdir}/qirc'

    unset -v \
     srcdir destdir pkgname pkgversion pkgcategory program version release \
     fetch description homepage license replace full_pkgname docs docsdir \
     CFLAGS CXXFLAGS LDFLAGS CPPFLAGS

    # The following variables must be restored, later
    save_arch="${save_arch:=$arch}"
    save_jobs="${save_jobs:=$jobs}"
    save_outdir="${save_outdir:=$outdir}"
    save_opt_nopkg="${save_opt_nopkg:=$opt_nopkg}"
    save_tarlz_compression_options="${save_tarlz_compression_options:=$tarlz_compression_options}"

    # Reset variable values in case of return
    arch="$save_arch"
    jobs="$save_jobs"
    outdir="$save_outdir"
    opt_nopkg="$save_opt_nopkg"
    tarlz_compression_options="$save_tarlz_compression_options"

    # The following variables cannot be redefined on a recipe
    readonly worktree netget rsync

    # Import the recipe

    . "${CWD}/$recipe"
    chkstatus_or_exit

    # Check if 'opt_skiprecipe' has been declared to ignore
    # the current recipe and continue with the next recipe
    if test "$opt_skiprecipe" = "opt_skiprecipe"
    then
        unset -v opt_skiprecipe
        warn "${recipe}: The variable 'opt_skiprecipe' has been used here."
        return 0;
    fi

    # Check for required variables
    if test -z "$program"
    then
        warn "${recipe}: The variable 'program' is not defined."
        exit 5
    fi
    if test -z "$version"
    then
        warn "${recipe}: The variable 'version' is not defined."
        exit 5
    fi
    if test -z "$arch"
    then
        warn "${recipe}: The variable 'arch' is not defined."
        exit 5
    fi
    if test -z "$release"
    then
        warn "${recipe}: The variable 'release' is not defined."
        exit 5
    fi

    # Pre-settings before to start building

    # Increment the release number if the option was given
    if test "$opt_incr_release" = opt_incr_release
    then
        release=$(( release + 1 ))
    fi

    # Allow the dot as definition for 'tardir'
    if test "$tardir" = .
    then
        tardir="$CWD"
    fi

    # Set default values for the following special variables

    pkgname="${pkgname:=$program}"
    pkgversion="${pkgversion:=$version}"
    srcdir="${srcdir:=${program}-$version}"
    destdir="${destdir:=${TMPDIR}/package-$pkgname}"

    # If 'pkgcategory' has been defined, prefix it using the "at" symbol
    if test -n "$pkgcategory"
    then
        pkgcategory="@${pkgcategory}"
    fi

    # Compose the full package name
    full_pkgname="${full_pkgname:=${pkgname}_${pkgversion}_${arch}-${release}${pkgcategory}}"

    # Use 'arch' as suffix for 'outdir' to have a well-organized package output
    outdir="${outdir}/${arch}"

    # If a package is going to be created the existence of a
    # previous build will be detected and reported.  Under normal
    # conditions the recipe is built as long as it is newer than
    # the produced package, if not, we warn to the user about it.
    # Rebuilding the package is possible (through the force ;-)

    if test "$opt_nopkg" != opt_nopkg && \
     { test "$opt_force" != opt_force && \
       test -e "${outdir}/${full_pkgname}.tlz" ; }
    then
        if is_newer "${CWD}/$recipe" "${outdir}/${full_pkgname}.tlz"
        then
            warn \
             ""                                                          \
             "This recipe is more RECENT than the produced package:"     \
             ""                                                          \
             "$( stat -c "%y %n" "${CWD}/$recipe" )"                     \
             "$( stat -c "%y %n" "${outdir}/${full_pkgname}.tlz" )"      \
             ""                                                          \
             "    This recipe will be processed ..."                     \
             ""
        elif test -e "${CWD}/post-install" && \
             is_newer "${CWD}/post-install" "${CWD}/$recipe"
        then
            warn \
             ""                                                          \
             "The post-install script is more RECENT than the recipe:"   \
             ""                                                          \
             "$( stat -c "%y %n" "${CWD}/post-install" )"                \
             "$( stat -c "%y %n" "${CWD}/$recipe" )"                     \
             ""                                                          \
             "    This recipe will be re-processed ..."                  \
             ""
             touch "${CWD}/$recipe"
        elif test "$opt_skipqsts" = opt_skipqsts
        then
            warn "Recipe for '${full_pkgname}.tlz':  [Ignored]." ""
            return 0
        else
            warn \
             ""                                                          \
             "This recipe ALREADY produced a package:"                   \
             "$( stat -c "%y %n" "${outdir}/${full_pkgname}.tlz" )"      \
             ""                                                          \
             "The recipe is still OLDER than the produced package:"      \
             "$( stat -c "%y %n" "${CWD}/$recipe" )"                     \
             ""                                                          \
             "    Probably nothing has changed."                         \
             ""

            # In non-interactive mode, the user is asked about
            # rebuilding the package.  In interactive mode,
            # the user need to pass the option explicitly
            if test ! -t 0
            then
                printf '%s\n' \
                 "Do you want to rebuild this package?"   \
                 "1) Yes, built it"                       \
                 "2) No, skip it [default]"               \
                 "3) Resume, skipping completed recipes"  \
                 "Enter an option number:" > /dev/tty
                IFS= read -r ANSWER < /dev/tty || exit 2;
                case $ANSWER in
                1*)
                    echo "$ANSWER" > /dev/tty
                    unset -v ANSWER
                    ;;
                3*)
                    unset -v ANSWER
                    echo "=== Building unprocessed or recently modified recipe(s) ..." > /dev/tty
                    echo ""
                    opt_skipqsts=opt_skipqsts
                    readonly opt_skipqsts
                    return 0
                    ;;
                *)
                    unset -v ANSWER
                    echo "Recipe for '${full_pkgname}.tlz':  Cancelled." > /dev/tty
                    echo ""
                    return 0
                    ;;
                esac
            else
                warn "Use the --force option to reprocess ${CWD}/${recipe}." ""
                return 6;
            fi
        fi
    fi

    # Fetch remote sources

    echo "=== Fetching remote sources if needed ..."
    if test -n "$fetch"
    then
        for origin in $fetch
        do
            echo "=== Looking for $origin ..."

            _source="${origin##*/}";	# Get the file name.

            echo "=== Verifying checksum file found \`${tardir}/${_source}.sha256'"
            if test -e "${tardir}/${_source}.sha256"
            then
                ( cd -- "$tardir" && sha256sum - ) < "${tardir}/${_source}.sha256"
                chkstatus_or_exit
                continue;
            else
                warn "    Checksum file \`${_source}.sha256' does not exist"
            fi

            # Download source or resume if allowed

            if test ! -e "${tardir}/$_source"
            then
                warn "=== Attempting to get it from $origin ..."
            fi

            case $origin in
            rsync://*)
                    (
                        cd -- "$tardir" && $rsync "$origin" || exit $?
                        sha256sum "$_source" > "${_source}.sha256"
                    );  chkstatus_or_exit 10
                ;;
            *://*)
                    (
                        cd -- "$tardir" && $netget "$origin" || exit $?
                        sha256sum "$_source" > "${_source}.sha256"
                    );  chkstatus_or_exit 10
                ;;
            *)
                warn "${PROGRAM}: Unrecognized protocol for ${origin}."
                exit 4
            esac
        done
        unset -v origin _source
    else
        warn "${recipe}: The variable 'fetch' is empty."
    fi

    # Prepare special directories for build the source,
    # the destination and the output of the package

    echo "=== Preparing directories ..."

    if test -z "$keep_srcdir"
    then
        if test -e "${TMPDIR}/$srcdir"
        then
            rm -rf -- "${TMPDIR:?}/$srcdir" || chkstatus_or_exit
            echo "removed directory: '${TMPDIR}/$srcdir'"
        fi
    else
        warn \
         "WARNING: The variable 'keep_srcdir' has been set (${keep_srcdir})."
    fi

    if test -z "$keep_destdir"
    then
        if test -e "$destdir"
        then
            rm -r -- "$destdir" || chkstatus_or_exit
            echo "removed directory: '$destdir'"
        fi
        mkdir -p -- "$destdir" || chkstatus_or_exit
        echo "mkdir: created directory '$destdir'"
    fi

    if test ! -e "$outdir"
    then
        mkdir -p -- "$outdir" || chkstatus_or_exit
        echo "mkdir: created directory '$outdir'"
    fi

    echo "=== Changing to '${TMPDIR}' ..."
    cd -- "$TMPDIR" || chkstatus_or_exit

    # Set trap before to run the build() function in order
    # to catch the return status, exit code 2 if fails

    trap 'chkstatus_or_exit 2' EXIT HUP INT QUIT ABRT TERM

    # Determine if the debugging indicators of the shell should be
    # retained, assuming that it has been previously passed
    case $- in *x*)
        _xtrace_flag=_xtrace_flag_is_set ;;
    esac

    echo "=== Running the 'build' function ..."
    build
    unset -f build

    # Check recipe to run (extra) defined functions by the packager
    for _definition in \
     $(awk '!/^build[ (]/ && /^[^ {}]+ *\(\)/{ gsub(/[()]/, "", $1); print $1 }' "${CWD}/$recipe")
    do
        # Check if it is a shell function
        case $(LC_ALL=C type $_definition) in
        *function*)
            # Call and undo the function after executing it
            $_definition
            unset -f $_definition
            ;;
        esac
    done
    unset -v _definition

    # Turn off possible shell flags coming from the recipe

    set +e
    if test "${_xtrace_flag:+$_xtrace_flag}" != _xtrace_flag_is_set
    then
        set +x
    fi

    # Reset given signals
    trap - EXIT HUP INT QUIT ABRT TERM

    # If 'destdir' is empty, the package won't be created
    if rmdir -- "$destdir" 2> /dev/null
    then
        warn "The package \"${full_pkgname}.tlz\" won't be created.  'destdir' is empty."
        opt_nopkg=opt_nopkg
    fi

    # Create (make) the package

    if test "$opt_nopkg" != opt_nopkg
    then
        # Edit the recipe when 'release' is incremented
        if test "$opt_incr_release" = opt_incr_release
        then
            echo ",s/^\\(release\\)=.*/\\1=${release}/"$'\nw' | \
             ed "${CWD}/$recipe" || chkstatus_or_exit
        fi

        mkdir -p -- "${destdir}/var/lib/qi" || chkstatus_or_exit

        # Include a copy of the recipe into the package
        cp -p "${CWD}/$recipe" \
              "${destdir}/var/lib/qi/${full_pkgname}.recipe" && \
         chmod 644 "${destdir}/var/lib/qi/${full_pkgname}.recipe"
        chkstatus_or_exit
        (
            # Produce a checksum file for recipe copy
            cd -- "${destdir}/var/lib/qi" && \
             sha256sum "${full_pkgname}.recipe" > "${full_pkgname}.recipe.sha256"
        ); chkstatus_or_exit 4

        # Detect post-install script for inclusion

        if test -f "${CWD}/post-install"
        then
            echo "${CWD}/post-install:  Detected."
            cp -p "${CWD}/post-install" \
                  "${destdir}/var/lib/qi/${full_pkgname}.sh" && \
             chmod 644 "${destdir}/var/lib/qi/${full_pkgname}.sh"
            chkstatus_or_exit
        fi

        # Detect declared package name(s) for later replacement

        if test -n "$replace"
        then
            warn \
             "=== The following package names has been declared for replacement:" \
             "$replace"

            : > "${destdir}/var/lib/qi/${full_pkgname}.replace"
            for item in $replace
            do
                printf '%s\n' "$replace" >> \
                 "${destdir}/var/lib/qi/${full_pkgname}.replace"
            done
            unset -v item
        fi

        # Create (external) meta file for package information,
        # make a copy of it for the package database
        echo "=== Creating meta file ${full_pkgname}.tlz.txt ..."
        do_meta > "${outdir}/${full_pkgname}.tlz.txt" || chkstatus_or_exit
        cp -p "${outdir}/${full_pkgname}.tlz.txt" \
          "${destdir}/var/lib/qi/${full_pkgname}.txt" || chkstatus_or_exit

        # Produce the package
        cd -- "$destdir" && mode_create "${outdir}/${full_pkgname}.tlz"
    fi

    # Back to the current working directory
    cd -- "$CWD" || chkstatus_or_exit

    echo "=== Deleting 'srcdir' or 'destdir' ..."
    if test "$opt_keep" != opt_keep
    then
        if test -z "$keep_srcdir"
        then
            srcdir="${srcdir%%/*}";	# Directory name without parents.
            if test -e "${TMPDIR}/$srcdir"
            then
                rm -rf -- "${TMPDIR:?}/$srcdir" || chkstatus_or_exit
                echo "removed directory: '${TMPDIR}/$srcdir'"
            fi
        fi
        if test -z "$keep_destdir"
        then
            if test -e "$destdir"
            then
                rm -rf -- "$destdir" || chkstatus_or_exit
                echo "removed directory: '$destdir'"
            fi
        fi
    else
        warn \
         "    The following directories will be preserved:"  \
         "${TMPDIR}/$srcdir"                                 \
         "$destdir"                                          \
         ""                                                  \
         "The '--keep' option has been used."
    fi

    # Install or upgrade the package after build
    if test "$opt_nopkg" != opt_nopkg
    then
        if test "$opt_install" = opt_install
        then
            mode_install "${outdir}/${full_pkgname}.tlz"
        elif test "$opt_upgrade" = opt_upgrade
        then
            mode_upgrade "${outdir}/${full_pkgname}.tlz"
        fi
    fi

    warn "{@} Recipe \"${CWD}/${recipe}\" has been processed." ""
}

mode_create()
{
    directory="$(dirname -- "$1")"

    # Perform sanity checks

    if ! fnmatch '/?*' "$directory"
    then
        warn "${PROGRAM}: Output directory \`${directory}' is not fully qualified"
        exit 4
    fi
    is_readable "$directory" || exit 4

    name="$(basename -- "$1")"

    echo ""
    echo "{#} Creating package name \`${name}' ..."

    if test "$name" = "${name%.tlz}"
    then
        warn "Package format '$name' not supported." \
             "It should be \"name_version_architecture-release[@pkgcategory].tlz\""
        exit 4
    fi

    # If needed, assign default values for compression options
    tarlz_compression_options="${tarlz_compression_options:=-9 --solid}"

    # Pass extra options to tarlz(1)
    if test -n "$SOURCE_DATE_EPOCH"
    then
        tarlz_compression_options="$tarlz_compression_options --mtime=@${SOURCE_DATE_EPOCH}"
    fi

    ( umask 022 ; tarlz $tarlz_compression_options -cvf - -- * ) > "${directory}/$name"
    chkstatus_or_exit 3

    ( cd -- "$directory" && sha256sum "$name" > "${name}.sha256" )
    chkstatus_or_exit 4

    warn "{#} Package \"${name}\" created on ${directory}." ""

    # Remove used variables
    unset -v directory name
}

mode_remove()
{
    expunge="${packagedir}/$(basename -- "$1" .tlz)"

    echo ""
    echo "{<} Removing \`$rootdir${expunge}' ..."

    # Complain if the package directory cannot be well-read

    is_readable "$rootdir${expunge}" || exit 4

    # Validate package directory as such

    test -d "$rootdir${expunge}" || {
        warn "Package '$rootdir${expunge}' is not a valid directory."
        exit 4
    }

    # Remove package from Graft control

    # Scan for possible conflicts, stop if arise
    if test "$opt_prune" != opt_prune
    then
        echo "=== Checking for possible conflicts ..."
        if graft -d -n $graft_r -t "$targetdir" "$expunge" 2>&1 | \
         grep "^CONFLICT"
        then
            warn "" \
             "    A conflict occurred during uninstallation;"  \
             "Unless the --prune option is given, this package will be PRESERVED."
            exit 6;
        fi
    fi

    # Remove objects (files, links or directories) from the target
    # directory that are in conflict with the package directory

    echo "=== Pruning any conflict ..."
    graft -p -D -u $graft_r -t "$targetdir" "$expunge"
    chkstatus_or_exit 2

    echo "=== Disabling links ..."
    graft -d -D -u $graft_v $graft_r -t "$targetdir" "$expunge"
    chkstatus_or_exit 2

    # Delete package directory
    if test "$opt_keep" != opt_keep
    then
        echo "=== Deleting package directory ..."
        if is_readable "${rootdir}$expunge"
        then
            rm -r -- "${rootdir}$expunge" || chkstatus_or_exit
            echo "removed directory: '${rootdir}$expunge'"
        fi
    fi

    warn "{<} Package \"${expunge##*/}\" removed from $rootdir${expunge%%/*}." ""
    unset -v expunge
}

mode_install()
{
    # Complain if the package cannot be well-read

    is_readable "$1" || exit 4

    # Complain if the package does not end in .tlz

    if ! fnmatch '*.tlz' "$1"
    then
        warn "\`${1}' does not end in .tlz"
        exit 4
    fi

    # Make preparations to install the package

    echo ""
    echo "{>} Installing $1 ..."

    echo "=== Checking tarball integrity ..."
    tarlz --missing-crc -tf "$1" > /dev/null
    chkstatus_or_exit 3

    # To accept random directory from the upgrade mode
    _packagedir="$2"
    _packagedir="${_packagedir:=$packagedir}"

    # Create package directory using 'name'

    name="$(basename -- "$1" .tlz)";		# Get the file name.

    if ! test -d "$rootdir${_packagedir}/$name"
    then
        mkdir -p -- "$rootdir${_packagedir}/$name" || chkstatus_or_exit
        echo "mkdir: created directory '$rootdir${_packagedir}/$name'"
    fi

    # Scan for possible conflicts, stop if arise
    if test "$opt_prune" != opt_prune
    then
        echo "=== Checking for possible conflicts ..."
        if graft -i -n $graft_r -t "$targetdir" "${_packagedir}/$name" 2>&1 | \
         grep "^CONFLICT"
        then
            warn "" \
             "    A conflict occurred during installation;"  \
             "Unless the --prune option is given, this package won't be LINKED."
             exit 6;
        fi
    fi

    echo "=== Decompressing package ..."
    ( cd -- "$rootdir${_packagedir}/$name" && tarlz -xpf - ) < "$1"
    chkstatus_or_exit 3

    # Transite package to Graft control

    # Remove objects (files, links or directories) from the target
    # directory that are in conflict with the package directory
    echo "=== Pruning any conflict ..."
    graft -p -D -u $graft_r -t "$targetdir" "${_packagedir}/$name"
    chkstatus_or_exit 2

    echo "=== Enabling symbolic links ..."
    graft -i -P $graft_v $graft_r -t "$targetdir" "${_packagedir}/$name"
    chkstatus_or_exit 2

    # Avoid unnecessary runs coming from the upgrade mode,
    # this is when the incoming package is **pre-installed**

    if test "$_isUpgrade" != _isUpgrade.on
    then
        # Show package description
        if test -r "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.txt"
        then
            awk '/^#/' "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.txt"
        elif test -r "${1}.txt"
        then
            # From external meta file (current directory)
            awk '/^#/' "${1}.txt"
        else
            warn "Description file not found for '$name'."
        fi

        # Check and run the post-install script if exist
        if test -r "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.sh"
        then
            echo "=== Running post-install script for \`${name}' ..."
            (
                # Rely on 'targetdir' if 'rootdir' is empty
                cd -- "${rootdir:=$targetdir}"/ && \
                 . "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.sh"
            )
        fi

        # Check if there are declared packages for replacement
        if test -r "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.replace"
        then
            while read -r line
            do
                for replace in "$rootdir${_packagedir}/${line%%_*}"_*
                do
                    if ! test -e "$replace"
                    then
                        warn "    Declared package \`${replace}' to be replaced does not exist.  [Ignored]"
                        continue;
                    fi

                    replace="${replace##*/}"

                    # The search for the package to be replaced cannot
                    # be the same to the incoming package, even to the
                    # temporary location coming from the upgrade mode
                    if test "$replace" = "$name" || \
                       test "_x_${replace}" = "_x_${PRVLOC##*/}"
                    then
                        continue;
                    fi

                    warn "WARNING: Replacing package \`${replace}' ..."

                    # Since the links belongs to the new package, only
                    # those which are not in conflict can be deleted.
                    # To complete, we will remove the package directory

                    graft -d -D -u $graft_r \
                     -t "$targetdir" "$replace" > /dev/null 2>&1

                    rm -rf -- "$rootdir${_packagedir}/$replace"
                done
            done < "$rootdir${_packagedir}/${name}/var/lib/qi/${name}.replace"
        fi
    fi

    warn "{>} Package \"${name}\" installed on $rootdir${_packagedir}." ""
    unset -v name _packagedir;	# Remove used variables.
}

mode_order()
{
    # Complain if the file cannot be well-read

    is_readable "$1" || exit 4

    # Complain if the file does not end in .order

    if ! fnmatch '*.order' "$1"
    then
        warn "\`${1}' does not end in .order"
        exit 4
    fi

    # Get a clean list of the file while printing its contents in
    # reverse order.  Last awk(1) in the pipeline eliminates
    # non-consecutive lines: duplicates, blank lines, and colons.
    # Comment lines beginning with '#' are allowed; parentheses
    # are simply ignored

    awk '{
     gsub( /:|^#(.*)$|\([^)]*)|^$/,"" );
      for( i=NF; i > 0; i-- ) print $i
    }' "$1" | awk '!s[$0]++'
}

mode_upgrade()
{
    # Complain if the package does not end in .tlz

    if ! fnmatch '*.tlz' "$1"
    then
        warn "\`${1}' does not end in .tlz"
        exit 4
    fi

    echo ""
    echo "{^} Upgrading $1 ..."

    incoming="$(basename -- "$1" .tlz)";	# Get the file name.

    # Check package pre-existence
    if test "$opt_force" != opt_force && \
       test -e "$rootdir${packagedir}/$incoming"
    then
        warn "" \
         "    The package to be upgraded already exist;" \
         "Unless the --force option is given, this package won't be UPGRADED."
        exit 6;
    fi

    # Ignore some signals until the upgrade process is complete
    trap "" HUP INT QUIT ABRT TERM

    # Check blacklisted packages before to proceed with the upgrade

    echo "=== Checking blacklist ..."
    for item in $blacklist
    do
        case $item in
        "${incoming%@*}"*)
            warn \
             "    A blacklisted package name has been detected:"            \
             "$incoming"                                                    \
             ""                                                             \
             "^ This package will be INSTALLED instead of being upgraded ..."
            opt_prune=opt_prune mode_install "$1"
            return 0;
            ;;
        esac
    done
    unset -v item

    # Prepare the package to install it in a temporary but custom location

    # Set random directory under 'rootdir/packagedir' using 'incoming' as name
    PRVLOC=$(mktemp -dp "$rootdir${packagedir}" ${incoming}.XXXXXXXXXXXX) || exit 2

    echo "=== Pre-installing package in temporary location ..."

    opt_prune=opt_prune;	# Turns on prune operation.

    _isUpgrade=_isUpgrade.on mode_install "$1" "$PRVLOC" > /dev/null
    _isUpgrade=_isUpgrade.off

    echo "=== Looking for installations under the same name ..."
    for previous_package in "$rootdir${packagedir}/${incoming%%_*}"_*
    do
        test -e "$previous_package" || continue

        # Previous package directory to be removed cannot be
        # the same to the temporary (private) location
        if test "$previous_package" = "$PRVLOC"
        then
            continue;
        fi

        # The directory of the package could be preserved if --keep
        mode_remove "$previous_package"
    done
    unset -v previous_package

    # Re-install incoming package to the final location

    mode_install "$1"
    opt_prune=opt_prune.off;	# Turns off prune operation.

    echo "=== Deleting temporary location ..."
    if is_readable "$PRVLOC"
    then
        rm -rf -- "$PRVLOC" || chkstatus_or_exit
        echo "removed directory: '$PRVLOC'"
    fi
    unset -v PRVLOC

    warn "{^} Package \"${incoming}\" upgraded for $rootdir${packagedir}." ""
    unset -v incoming

    # Reset given signals
    trap - HUP INT QUIT ABRT TERM
}

mode_warn()
{
    # Complain if the package cannot be well-read

    is_readable "$1" || exit 4

    # Complain if the package does not end in .tlz

    if ! fnmatch '*.tlz' "$1"
    then
        warn "\`${1}' does not end in .tlz"
        exit 4
    fi

    # List content of files excluding directories
    while test -f "$1"
    do
        tarlz -tvvf "$1" | awk '!/^drwx/'
        chkstatus_or_exit 3
        shift;
    done
    return 0
}

mode_extract()
{
    # Perform sanity checks before package extraction

    is_readable "$1" || exit 4

    test -f "$1" || {
        warn "\`${1}' is not a regular file."
        exit 4
    }

    # Preparations to extract the package

    name="$(basename -- "$1" .tlz)"

    # Set random directory under 'TMPDIR' using 'name'
    PRVDIR=$(mktemp -dp "$TMPDIR" ${name}.XXXXXXXXXXXX) || exit 2

    # Trap to remove 'PRVDIR' on disruptions
    trap 'rm -rf -- "$PRVDIR"' HUP INT ABRT TERM

    # Create 'PRVDIR' removing access for all but user
    ( umask 077 ; mkdir -- "$PRVDIR" )
    mkdir -p -- "$PRVDIR"
    chmod 700 -- "$PRVDIR"

    echo ""
    echo "{-} Extracting package \`${name}' ..."

    ( umask 000 ; cd -- "$PRVDIR" && tarlz -xvf - ) < "$1"
    if test $? -ne 0
    then
        # Try to remove (empty) 'PRVDIR' on failure
        rmdir -- "$PRVDIR"
        exit 3;
    fi

    warn "" "{-} Package \"${name}\" has been extracted on ${PRVDIR}."

    # Remove used variables
    unset -v name PRVDIR

    # Reset given signals
    trap - HUP INT ABRT TERM
}

### Extra functions to be used during the modes

unpack()
{
    for file in "$@"
    do
        case $file in
        *.tar)
            tar -tf "$file" > /dev/null && \
            tar -xpf "$file"
            chkstatus_or_exit 3
            ;;
        *.tar.gz | *.tgz | *.tar.Z )
            gzip -cd "$file" | tar -tf - > /dev/null && \
            gzip -cd "$file" | tar -xpf -
            chkstatus_or_exit 3
            ;;
        *.tar.bz2 | *.tbz2 | *.tbz )
            bzip2 -cd "$file" | tar -tf - > /dev/null && \
            bzip2 -cd "$file" | tar -xpf -
            chkstatus_or_exit 3
            ;;
        *.tar.lz | *.tlz )
            lzip -cd "$file" | tar -tf - > /dev/null && \
            lzip -cd "$file" | tar -xpf -
            chkstatus_or_exit 3
            ;;
        *.tar.xz | *.txz )
            xz -cd "$file" | tar -tf - > /dev/null && \
            xz -cd "$file" | tar -xpf -
            chkstatus_or_exit 3
            ;;
        *.tar.zst | *.tzst )
            zstd -cd "$file" | tar -tf - > /dev/null && \
            zstd -cd "$file" | tar -xpf -
            chkstatus_or_exit 3
            ;;
        *.zip | *.ZIP )
            unzip -t "$file" > /dev/null && \
            unzip "$file" > /dev/null
            chkstatus_or_exit 3
            ;;
        *.gz)
            gzip -t "$file" && \
            gzip -cd "$file" > "$(basename -- "$file" .gz)"
            chkstatus_or_exit 3
            ;;
        *.Z)
            gzip -t "$file" && \
            gzip -cd "$file" > "$(basename -- "$file" .Z)"
            chkstatus_or_exit 3
            ;;
        *.bz2)
            bzip2 -t "$file" && \
            bzip2 -cd "$file" > "$(basename -- "$file" .bz2)"
            chkstatus_or_exit 3
            ;;
        *.lz)
            lzip -t "$file" && \
            lzip -cd "$file" > "$(basename -- "$file" .lz)"
            chkstatus_or_exit 3
            ;;
        *.xz)
            xz -t "$file" && \
            xz -cd "$file" > "$(basename -- "$file" .xz)"
            chkstatus_or_exit 3
            ;;
        *.zst)
            zstd -qt "$file" && \
            zstd -cd "$file" > "$(basename -- "$file" .zst)"
            chkstatus_or_exit 3
            ;;
        *)
            warn "${PROGRAM}: cannot unpack ${file}: Unsupported extension"
            exit 1
        esac
    done
    unset -v file
}

do_meta()
{
    # Extract information from the recipe to create the meta file.
    #
    # The package description is pre-formatted in 78 columns,
    # the '#' character and a space is added as prefix to conform
    # the 80 columns in total
    printf '%s\n' "$description" | fold -w 78 | awk '$0="# " $0'

    # Include build flags only if it is a real architecture
    if test "$arch" != noarch
    then
        printf '%s' \
"
QICFLAGS=\"$QICFLAGS\"
QICXXFLAGS=\"$QICXXFLAGS\"
QILDFLAGS=\"$QILDFLAGS\"
QICPPFLAGS=\"$QICPPFLAGS\""
    fi

    # Print saving the rest of the package information
    printf '%s' \
"
pkgname=$pkgname
pkgversion=$pkgversion
arch=$arch
release=$release
pkgcategory=\"${pkgcategory#@*}\"
full_pkgname=$full_pkgname
blurb=\"$(printf '%s\n' "$description" | sed -e '/^$/d;2q')\"
homepage=\"$homepage\"
license=\"$license\"
fetch=\"$fetch\"
replace=\"$replace\"
"
}

### Default values

packagedir=@PACKAGEDIR@
targetdir=@TARGETDIR@
blacklist="perl5 graft tarlz plzip musl glibc coreutils bash mksh"
_rcfile=@SYSCONFDIR@/qirc
opt_install=opt_install.off
opt_upgrade=opt_upgrade.off
opt_force=opt_force.off
opt_keep=opt_keep.off
opt_incr_release=opt_incr_release.off
opt_skipqsts=opt_skipqsts.off
opt_nopkg=opt_nopkg.off
opt_prune=opt_prune.off
verbose_level=0
opt_skiprecipe=""
rootdir=""
arch=@ARCH@
jobs=1
mode=""
_xtrace_flag=""
_readstdin=""
graft_v=""
graft_r=""
_isUpgrade=_isUpgrade.off
keep_srcdir=""
keep_destdir=""
TMPDIR="${TMPDIR:-/usr/src/qi/build}"
QICFLAGS="${QICFLAGS:--O2}"
QICXXFLAGS="${QICXXFLAGS:--O2}"
QILDFLAGS="${QILDFLAGS:-}"
QICPPFLAGS="${QICPPFLAGS:-}"
worktree=/usr/src/qi
tardir=${worktree}/sources
outdir=/var/cache/qi/packages
netget="wget2 -c -w1 -t3 --no-check-certificate"
rsync="rsync -v -a -L -z -i --progress"
tarlz_compression_options="-9 --solid"
configure_args="--prefix=@PREFIX@ --libexecdir=@LIBEXECDIR@ --bindir=@BINDIR@ --sbindir=@SBINDIR@ --sysconfdir=@SYSCONFDIR@ --localstatedir=@LOCALSTATEDIR@"
infodir=@INFODIR@
mandir=@MANDIR@
docdir=@DOCDIR@

# Store (default) directory locations
QI_TARGETDIR=$targetdir
QI_PACKAGEDIR=$packagedir
QI_WORKTREE=$worktree
QI_TARDIR=$tardir
QI_OUTDIR=$outdir

### Parse commands and options

validate_mode()
{
    if test -n "$mode"
    then
        warn "${PROGRAM}: First defined command: ${mode#*_}" \
             "Switching to another command is not allowed (${1})."
        exit 1
    fi
}

validate_option()
{
    if test -z "$2"
    then
        warn "${PROGRAM}: The '${1}' option requires an argument" \
             "Try '${PROGRAM} --help' for more information."
        exit 1
    fi
}

validate_directory()
{
    if test ! -d "$2"
    then
        warn "${PROGRAM}: ${1} \"${2}\" must be a valid directory name"
        exit 1
    fi
}

validate_digit()
{
    name="$1"
    shift

    # Taken from https://mywiki.wooledge.org/BashFAQ/054
    case "${1#[-+]}" in
    '')
        warn "${PROGRAM}: The '${name}' option has no defined value"
        exit 1
        ;;
    *.*.*)
        warn "${PROGRAM}: The '${name}' option has more than one decimal point on it \"${1}\""
        exit 1
        ;;
    *[!0-9]*)
        warn "${PROGRAM}: The '${name}' option contains a non-valid digit on it \"${1}\""
        exit 1
        ;;
    esac

    unset -v name
}

while test $# -gt 0
do
    case $1 in
    warn)
        validate_mode warn
        mode=mode_warn
        ;;
    install)
        validate_mode install
        readconfig
        mode=mode_install
        ;;
    remove)
        validate_mode remove
        readconfig
        mode=mode_remove
        ;;
    upgrade)
        validate_mode upgrade
        readconfig
        mode=mode_upgrade
        ;;
    extract)
        validate_mode extract
        mode=mode_extract
        ;;
    create)
        validate_mode create
        mode=mode_create
        ;;
    order)
        validate_mode order
        mode=mode_order
        ;;
    build)
        validate_mode build
        readconfig
        mode=mode_build
        ;;
    --no-rc | -N )
        _readconfig=readconfig.off
        ;;
    --install | -i )
        opt_install=opt_install
        ;;
    --upgrade | -u )
        opt_upgrade=opt_upgrade
        ;;
    --force | -f )
        opt_force=opt_force
        ;;
    --keep | -k )
        opt_keep=opt_keep
        ;;
    --prune | -p )
        opt_prune=opt_prune
        ;;
    --packagedir | -P )
        validate_option "$1" "$2"
        packagedir="$2"
        validate_directory "$1" "$packagedir"
        shift
        ;;
    --packagedir=*)
        validate_option "$1" "$2"
        packagedir="${1#*=}"
        validate_directory "$1" "$packagedir"
        ;;
    --targetdir | -t )
        validate_option "$1" "$2"
        targetdir="$2"
        validate_directory "$1" "$targetdir"
        shift
        ;;
    --targetdir=*)
        validate_option "$1" "$2"
        targetdir="${1#*=}"
        validate_directory "$1" "$targetdir"
        ;;
    --rootdir | -r )
        validate_option "$1" "$2"
        rootdir="$2"
        validate_directory "$1" "$rootdir"
        shift
        ;;
    --rootdir=*)
        validate_option "$1" "$2"
        rootdir="${1#*=}"
        validate_directory "$1" "$rootdir"
        ;;
    --outdir | -o )
        validate_option "$1" "$2"
        outdir="$2"
        validate_directory "$1" "$outdir"
        shift
        ;;
    --outdir=*)
        validate_option "$1" "$2"
        outdir="${1#*=}"
        validate_directory "$1" "$outdir"
        ;;
    --worktree | -w )
        validate_option "$1" "$2"
        worktree="$2"
        validate_directory "$1" "$worktree"
        shift
        ;;
    --worktree=*)
        validate_option "$1" "$2"
        worktree="${1#*=}"
        validate_directory "$1" "$worktree"
        ;;
    --sourcedir | -s )
        validate_option "$1" "$2"
        tardir="$2"
        validate_directory "$1" "$tardir"
        shift
        ;;
    --sourcedir=*)
        validate_option "$1" "$2"
        tardir="${1#*=}"
        validate_directory "$1" "$tardir"
        ;;
    --architecture | -a )
        validate_option "$1" "$2"
        arch="$2"
        shift
        ;;
    --arch=*)
        validate_option "$1" "$2"
        arch="${1#*=}"
        ;;
    --jobs | -j )
        jobs="$2"
        validate_digit "$1" "$jobs"
        shift
        ;;
    -j[0-9]*)
        jobs="${1#-j*}"
        validate_digit '-j' "$jobs"
        ;;
    --jobs=*)
        jobs="${1#*=}"
        validate_digit '--jobs=' "$jobs"
        ;;
    --no-package | -n )
        opt_nopkg=opt_nopkg
        ;;
    --increment | -1 )
        opt_incr_release=opt_incr_release
        ;;
    --skip-questions | -S )
        opt_skipqsts=opt_skipqsts
        ;;
    --verbose | -v )
        verbose_level=$(( verbose_level + 1 ))
        ;;
    -vv)
        # A trick for a second -v.
        verbose_level=2
        ;;
    --show-location | -L )
        printf '%s\n' \
         "QI_TARGETDIR=$QI_TARGETDIR"   \
         "QI_PACKAGEDIR=$QI_PACKAGEDIR" \
         "QI_WORKTREE=$QI_WORKTREE"     \
         "QI_TARDIR=$QI_TARDIR"         \
         "QI_OUTDIR=$QI_OUTDIR"
        exit 0
        ;;
    --help | --hel | --he | --h | '--?' | -help | -hel | -he | -h | '-?' | \
     help )
        usage
        exit 0
        ;;
    --version | --versio | --versi | --vers | \
     -version |  -versio |  -versi |  -vers | -V | version )
        echo "$PROGRAM version @VERSION@"
        exit 0
        ;;
    '-')
        _readstdin=readstdin
        break
        ;;
    --)
        shift
        break;	# End of options.
        ;;
    -*)
        warn "qi: Unrecognized option: $1" \
             "Try '${PROGRAM} --help' for more information."
        exit 1
        ;;
    *)
        break;	# No more options.
        ;;
    esac
    shift
done
unset -f readconfig validate_mode validate_option validate_directory validate_digit

# When there are no arguments, show the help
if test $# -eq 0
then
    usage
    exit 1
fi
unset -f usage

# Program sanity check

for need in awk basename chmod cp dirname find fold graft grep \
            mkdir mktemp rm rmdir sed sha256sum stat tarlz ; \
do
    if ! \command -v $need > /dev/null
    then
        warn "${PROGRAM}: Prerequisite \`${need}' not found in PATH"
        exit 2
    fi
done
unset -v need

# Set verbosity level and flags

if test "$verbose_level" -gt 0
then
    if test "$verbose_level" -eq 1
    then
        graft_v=-v
    else
        graft_v=-V
    fi
fi

# Read standard input if FILE is -, or when
# FILE is not connected to a terminal

if test "$_readstdin" = readstdin
then
    if test -t 0
    then
        warn "qi: I won't read from a connected terminal." \
             "Try '${PROGRAM} --help' for more information."
        exit 1
    fi

    # Unset positional parameters setting $# to zero
    set --

    # Assign remaining arguments to the positional parameters
    while read -r input
    do
        set -- "$@" "$input"
    done
fi
unset -v _readstdin

if test -z "$mode"
then
    warn "qi: We need at least one (valid) command." \
         "Try '${PROGRAM} --help' for more information."
    exit 4
fi

# Validate 'packagedir' and 'targetdir' as canonical directories

# The single slash '/' does not qualify here
if ! fnmatch '/?*' "$packagedir"
then
    warn "${PROGRAM}: Package directory \`${packagedir}' is not fully qualified"
    exit 4
fi
if test ! -d "$packagedir"
then
    warn "${PROGRAM}: Package directory \`${packagedir}' does not exist"
    exit 4
fi

# The single slash '/' is valid here
if ! fnmatch '/*' "$targetdir"
then
    warn "${PROGRAM}: Target directory \`${targetdir}' is not fully qualified"
    exit 4
fi
if test ! -d "$targetdir"
then
    warn "${PROGRAM}: Target directory \`${targetdir}' does not exist"
    exit 4
fi

# Validate 'rootdir' directory

if test -n "$rootdir"
then
    if test -d "$rootdir" && test "$rootdir" != /
    then
        rootdir="${rootdir%/}"	# Remove slash from the end.

        # A workaround for graft-2.13+.  The specified directory is
        # relative to the log file, we prepend it inside 'rootdir'

        eval "$(graft -L)" ; GRAFT_LOGFILE="${GRAFT_LOGFILE:=/var/log/graft}"
        mkdir -p -- "$rootdir$(dirname -- "$GRAFT_LOGFILE")" || chkstatus_or_exit

        # Compose 'rootdir' and log file option to be used with graft(1)
        graft_r="-r $rootdir -l $GRAFT_LOGFILE"

        # Unset variables coming from eval
        unset -v GRAFT_PERL GRAFT_LOGFILE GRAFT_TARGETDIR GRAFT_PACKAGEDIR
    else
        warn "${PROGRAM}: Root directory \`${rootdir}' is not fully qualified"
        exit 4
    fi
    readonly rootdir
    export rootdir
fi

# Ensure 'TMPDIR' creation to prefix temporary files

if test ! -d "$TMPDIR"
then
    mkdir -p -- "$TMPDIR" || chkstatus_or_exit
fi
readonly TMPDIR packagedir targetdir

# Process each package or recipe provided on the command-line

for package in "$@"
do
    $mode "$package"
done


code:
# Build recipe for programName.
#
# Copyright (c) Year(s) YourName, <email>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

program=
version=
release=1

# Define a category for the output of the package name
pkgcategory=

tarname=${program}-${version}.tar.gz

# Remote source(s)
fetch=

description="
Brief description.

Long description (preferably in 75 or 80 columns).
"

homepage=
license=

# Source documentation
docs=""
docsdir="${docdir}/${program}-${version}"

build()
{
    unpack "${tardir}/$tarname"

    cd "$srcdir"

    # Set sane permissions
    chmod -R u+w,go-w,a+rX-s .

    ./configure CPPFLAGS="$QICPPFLAGS" \
    CFLAGS="$QICFLAGS" CXXFLAGS="$QICXXFLAGS" LDFLAGS="$QILDFLAGS" \
     $configure_args \
     --libdir=/usr/lib${libSuffix} \
     --infodir=$infodir \
     --mandir=$mandir \
     --docdir=$docsdir \
     --build="$(gcc -dumpmachine)"

    make -j${jobs} V=1
    make -j${jobs} DESTDIR="$destdir" install

    # Compress info documents deleting index file for the package
    if test -d "${destdir}/$infodir"
    then
        rm -f "${destdir}/${infodir}/dir"
        lzip -9 "${destdir}/${infodir}"/*
    fi

    # Compress and link man pages (if needed)
    if test -d "${destdir}/$mandir"
    then
        (
            cd "${destdir}/$mandir"
            find . -type f -exec lzip -9 {} +
            find . -type l | while read -r file
            do
                ln -sf "$(readlink -- "$file").lz" "${file}.lz"
                rm -- "$file"
            done
        )
    fi

    # Copy documentation
    mkdir -p "${destdir}/$docsdir"
    cp -p $docs "${destdir}/$docsdir"
}