#!/bin/sh
#| cl-launch.sh -- shell wrapper for Common Lisp -*- Lisp -*-
CL_LAUNCH_VERSION='4.1.3'
license_information () {
AUTHOR_NOTE="\
# Please send your improvements to the author:
# fare at tunes dot org < http://www.cliki.net/Fare%20Rideau >.
"
SHORT_LICENSE="\
# cl-launch is available under the terms of the bugroff license.
#       http://tunes.org/legalese/bugroff.html
# You may at your leisure use the MIT license instead < http://opensource.org/licenses/MIT >
"
WEB_SITE="# For the latest version of cl-launch, see its web page at:
#       http://www.cliki.net/cl-launch
"
LICENSE_COMMENT="\
# This software can be used in conjunction with any other software:
# the result may consist in pieces of the two software glued together in
# a same file, but even then these pieces remain well distinguished, and are
# each available under its own copyright and licensing terms, as applicable.
# The parts that come from the other software are subject to the terms of use
# and distribution relative to said software, which may well be
# more restrictive than the terms of this software (according to lawyers
# and the armed henchmen they got the taxpayers to pay to enforce their laws).
# The bits of code generated by cl-launch, however, remain available
# under the terms of their own license, and you may service them as you wish:
# manually, using cl-launch --update or whichever means you prefer.
# That said, if you believe in any of that intellectual property scam,
# you may be subject to the terms of my End-Seller License:
#       http://www.livejournal.com/users/fare/21806.html
"
DISCLAIMER="\
# This file was automatically generated and contains parts of CL-Launch
"
}
license_information

### Settings for the current installation -- adjust to your convenience
### Or see documentation for using commands -B install and -B install_bin.
DEFAULT_LISPS="sbcl clisp ccl ecl cmucl gclcvs lispworks allegro gcl abcl scl"
DEFAULT_INCLUDE_PATH=
DEFAULT_USE_CL_LAUNCHRC=""
DEFAULT_USE_CLBUILD=""
DEFAULT_USE_QUICKLISP=""

### Initialize cl-launch variables
unset \
        SOFTWARE_BUILD_FORMS SOFTWARE_FINAL_FORMS SOFTWARE_INIT_FORMS \
        SOURCE_REGISTRY INCLUDE_PATH LISPS WRAPPER_CODE \
        OUTPUT_FILE UPDATE LISP_CONTENT \
        LINE LINE1 LINE2 NO_QUIT \
        TRIED_CONFIGURATION HAS_CONFIGURATION \
        EXEC_LISP DO_LISP DUMP LOAD_IMAGE RESTART RESTART_PACKAGE IMAGE IMAGE_OPT \
        EXTRA_CONFIG_VARIABLES \
        EXECUTABLE_IMAGE STANDALONE_EXECUTABLE CL_LAUNCH_STANDALONE \
        CL_LAUNCH_FILE __CL_ARGV0 IS_X_SCRIPT DISPATCH_ENTRY_P \
        TEST_SHELLS TORIG IMPL

LISPS="$DEFAULT_LISPS"
INCLUDE_PATH="$DEFAULT_INCLUDE_PATH"
USE_CL_LAUNCHRC="$DEFAULT_USE_CL_LAUNCHRC"
USE_CLBUILD="$DEFAULT_USE_CLBUILD"
USE_QUICKLISP="$DEFAULT_USE_QUICKLISP"

UNREAD_DEPTH=0
OUTPUT_FILE="!"
PACKAGE=cl-user
RESTART_PACKAGE=
INIT_PACKAGE=
FINAL_PACKAGE=

### Other constants
MAGIC_MD5SUM="65bcc57c2179aad145614ec328ce5ba8" # Greenspun's Tenth Rule...
CONTENT_DISCLAIMER="\
;;; THE SOFTWARE AFTER THIS MARKER AND TO THE END OF THE FILE IS NOT PART OF
;;; CL-LAUNCH BUT A PIECE OF SOFTWARE DISTINCT FROM CL-LAUNCH. IT IS OWNED BY
;;; BY ITS OWNERS AND IS SUBJECT ITS OWN INDEPENDENT TERMS OF AVAILABILITY."
CONTENT_BEGIN_MARKER="\
;;; ${MAGIC_MD5SUM} SOFTWARE WRAPPED BY CL-LAUNCH BEGINS HERE:"

### Help
## setup a few environment variables for the program
BASIC_ENV_CODE='PROG="$0"'
eval "$BASIC_ENV_CODE"

PROGBASE="${0##*/}" # "$(basename "$0")"

CL_LAUNCH_URL="http://fare.tunes.org/files/cl-launch/cl-launch.sh"

HELP_HEADER="cl-launch.sh $CL_LAUNCH_VERSION \"(April 2015)\" \"Francois-Rene Rideau's\" \"shell wrapper for Common Lisp\""
print_help_header () {
  ECHO "$HELP_HEADER"
  ECHO "============"
}
print_help () {
cat <<EOF
Name
----
cl-launch - shell wrapper for Common Lisp

Synopsis
--------
    $PROGBASE [options] '(lisp (form) to evaluate)'
        evaluate specified form, print the results followed by newline
        as in: cl -l sbcl -sp my-system-and-package '(some form)'

    $PROGBASE [options] script-file arguments...
        run specified Lisp script, passing arguments, as in a script with
        #!/usr/bin/cl -sp my-system-and-package -E main

    $PROGBASE [options] [--execute] [options] [-- arguments...]
        run the specified software without generating a script (default)

    $PROGBASE [options] --output EXECUTABLE [options]
        generate an executable script or binary from the software specification

Special modes
-------------
    -h  or  -?  --help           display a short help message
    -H          --more-help      show complete help (you may use a \$PAGER)
    -V          --version        display cl-launch version and configuration
    -u FILE     --update FILE    update a cl-launch script to current version

Software specification
----------------------
    -w CODE     --wrap CODE          shell wrapper CODE to run in cl-launch
    -l LISP...  --lisp LISP...       try use these LISP implementations
    -m IMAGE    --image IMAGE        build from Lisp image IMAGE
    -f FILE     --file FILE          include lisp FILE while building
    -L FILE     --load FILE          load lisp FILE while building
    -S X        --source-registry X  override source registry of asdf systems
    -s SYSTEM   --system SYSTEM      load asdf SYSTEM while building
                --load-system SYSTEM same as above (buildapp compatibility)
    -p PACKAGE  --package PACKAGE    change current package to PACKAGE
    -sp SP      --system-package SP  combination of -s SP and -p SP
    -e FORM     --eval FORM          evaluate FORM while building
                --require MODULE     require MODULE while building
    -r FUNC     --restart FUNC       restart from build by calling (FUNC)
    -E FUNC     --entry FUNC         restart from build by calling (FUNC argv)
    -DE N/F  --dispatched-entry N/F  if exec'ed as N, restart from (F argv)
    -i FORM     --init FORM          evaluate FORM after restart
    -ip FORM    --print FORM         evaluate and princ FORM after restart
    -iw FORM    --write FORM         evaluate and write FORM after restart
    -F FORM     --final FORM         evaluate FORM before dumping IMAGE
    -I PATH     --include PATH       runtime PATH to cl-launch installation
    +I          --no-include         disable cl-launch installation feature
    -R          --rc                 try read /etc/cl-launchrc, ~/.cl-launchrc
    +R          --no-rc              skip /etc/cl-launchrc, ~/.cl-launchrc
    -Q          --quicklisp          use quicklisp (see --more-help)
    +Q          --no-quicklisp       do not use quicklisp
    -b          --clbuild            use clbuild (see --more-help)
    +b          --no-clbuild         do not use clbuild
    -v          --verbose            be quite noisy while building
    -q          --quiet              be quite quiet while building (default)

Output options
--------------
    -x   -o !   --execute            run the specified software NOW (default)
    -o FILE     --output FILE        create executable FILE
    -d IMAGE    --dump IMAGE         dump IMAGE for faster startup
    -X ... --   (see more help)      use #!/.../cl-launch as script interpreter
    --          --                   end of arguments when using -x or -X
EOF
}
print_help_footer () {
  cat<<EOF
See our web page on:
        <http://www.cliki.net/cl-launch>

Note: if this help is too long for you, you may scroll back, or use:

        $PROGBASE --more-help | less

EOF
}
print_more_help () {
cat<<EOF
Invocation of cl-launch
-----------------------

\`cl-launch\` will evaluate Common Lisp code or create shell scripts or
executable binaries that evaluate Common Lisp code. cl-launch follows
the invocation conventions of both Unix script interpreters
and Common Lisp implementations.

A suggested short-hand name for \`cl-launch\` is \`cl\` (you may create a
symlink if it isn't included in your operating system's \`cl-launch\` package).
We'd like to homestead the path \`/usr/bin/cl\` while we can, so that
script authors can reasonably expect a script to work when it starts with:
        \`#!/usr/bin/cl\`
(See *Simple cl-launch scripts* below for caveats with \`#!\` scripts though.)
Recent Linux kernels support a script interpreter itself being a script;
BSD kernels don't and require a small C program cl-shim to be compiled and
installed as /usr/bin/cl to use cl-launch this way.

To work properly, \`cl-launch\` 4.1.3 depends on \`ASDF\` 3.1.2 or later, and
on its portability layer \`UIOP\`, to manage compilation and image life cycle.

The software is specified as the evaluation of code in several phases;
the distinction matters most for creating executable binaries,
but understanding the evaluation model can avoid surprises in other cases too.

In the first phase, the Lisp image is initialized:

* optionally having your Lisp start from a Lisp \`IMAGE\`
  (option \`-I --image\`)
* loading a small header of code that provides common \`cl-launch\` functionality
* loading \`ASDF3\`.
  The \`cl-launch\` header will try hard to load \`ASDF 3.1.2\` or later.
  If your implementation does not provide it via \`(require "asdf")\`,
  you can configure your implementation's \`ASDF\` (if any) to find it.
  Or you can put it in your home, under \`~/common-lip/asdf/\`
  and \`cl-launch\` will find it.
  Or it may be installed in \`/usr/share/common-lisp/source/cl-asdf/\`
  in which case \`cl-launch\` will also find it.
  Failing any of the above, \`cl-launch\` will be unable to proceed.
* optionally loading [quicklisp](http://beta.quicklisp.org/)
  (option \`-Q --quicklisp\`)

In a second phase, your software is built, based on the following options,
in order of appearance:

* evaluating one or several \`FORMS\` (option \`-e --eval\`)
  in the current package. The series of forms is evaluated
  as by \`LOAD\`, in a context where the \`*package*\`
  has been set to the current package (see below explanations on packages).
* compiling a \`FILE\` and load the fasl (option \`-L --load\`)
  Files are loaded with \`*package*\` bound to the current package (see below).
* including a \`FILE\`, compiling it and loading the fasl (option \`-f --file\`)
  The contents of the \`FILE\`, which will have be included in the output script,
  will be compiled and the fasl loaded as if by option \`-L --load\`.
  The difference matters mostly when creating an output script,
  as opposed to executing the code immediately or dumping an image.
  Only one file may be specified this way.
  If a filename specified with \`-f --file\` is \`-\` (after stripping quotes),
  then the standard input is used. You may thus concatenate several files
  and feed them to \`cl-launch\` through a pipe.
  To use a file named \`-\`, pass the argument \`./-\`
  (same trick as for \`cat\` and other Unix commands).
* A script file, as specified by \`-X ... --\` or by use of \`#!\`
  or by following options with an immediate filename that does not start with
  \`(\` or \`-\`, counts as if preceded by \`--package cl-user --load\`
  and followed by \`--execute --\`
* requiring an implementation-provided \`MODULE\` (option \`--require\`)
* having \`ASDF3\` compile and load a \`SYSTEM\`
  (option \`-s --system --load-system\`).
  Option \`-sp --system-package\` loads the \`SYSTEM\` like \`-s --system\`
  and also changes the current \`*package*\` like \`-p --package\`
  (see below on packages).
* optionally having your Lisp \`DUMP\` an image to restart from
  (option \`-d --dump\`), and just before
  evaluating one or several \`FINAL\` forms (option \`-F --final\`).
  See section *Dumping images*.

If you are creating a shell script with option \`-o --output\` but
without using option \`-d --dump\`, then these first two phases only happen
when the script is invoked. If you are using option \`-d --dump\`,
then these two phases happen immediately, and
no compilation happen when invoking the output.
Note that compiled files are cached, so that the compilation only happens
the first time a file is loaded via \`--load of --system\`,
or if the source file has been modified.
This may cause slower startup the first time over.
The cache is controlled by \`ASDF\`'s \`output-translations\` mechanism.
See your \`ASDF\` manual regarding the configuration of this cache,
which is typically under \`~/.cache/common-lisp/\`

In a third phase, your software is run via \`UIOP:RESTORE-IMAGE\`.
This happens immediately if using option \`-x --execute\` or
calling \`cl-launch\` as a Unix interpreter on a script e.g. via \`#!\`;
or it can happen later if you use option \`-o --output\` in combination
with (or without) option \`-d --dump\` to dump an image (which gives you faster
startup and single-file or double-file delivery, at the expense of disk space),
at which point it happens when you invoke the executable output file:

* Hooks from \`ASDF3\`'s \`UIOP:*IMAGE-RESTORE-HOOK*\` are called
  (in FIFO order).
* a series of \`FORMS\` specified via options \`-i --init\`,
  \`-ip --print\`, \`-iw --write\`, stored as a text string,
  are read and evaluated in order of appearance, each in the context
  of the package that was current at the time it was requested.
  (Concatenated together with separating whitespace, these forms constitute
  the \`UIOP:*IMAGE-PRELUDE*\` as handled by \`RESTORE-IMAGE\`).
  Arguments that start with an open parenthesis are assumed to be \`FORMS\`
  that follow an implicit \`--print\`.
  Loading from a stream means you don't have to worry about nasty read-time
  issues; forms will be read by the fully built Lisp image; however it also
  means that if you care a lot about the very last drop of startup delay when
  invoking a dumped image, you'll only use option \`-r --restart\`
  or \`-E --entry\` and avoid using \`--init\` and its variants.
  Option \`-ip --print\` specifies \`FORMS\` such that the result of
  the last form will be printed as if by \`PRINC\`, followed by a newline.
  Option \`-iw --write\` is similar to \`--print\`,
  using \`WRITE\` instead of \`PRINC\`.
* An optional \`FUNCTION\` provided option \`-r --restart\` or \`-E --entry\`
  is invoked. If the function was provided with option \`-r --restart\`
  (compatible with earlier versions of \`cl-launch\`),
  it will be called with no argument. If it was provided with
  option \`-E --entry\` (compatible with \`buildapp\`), it will be called
  with one argument, being the list of arguments passed to the program,
  not including \`argv[0]\`, which is available on most implementations via the
  function \`uiop:argv0\` (available in \`ASDF\` 3.1.2 and later).
  Using either option, the argument may be a function name
  or a lambda expression, that is read from the current package
  (see below option \`-p --package\` and \`-sp --system-package\`).
  Only one restart or entry function may be specified;
  if multiple are provided, the last one provided overrides previous ones.
  If you want several functions to be called, you may \`DEFUN\` one that calls
  them and use it as a restart, or you may use multiple init forms as below.
  See also below options \`-DE --dispatch-entry\`, \`-sm --system-main\`,
  \`-Ds --dispatch-system\` that behave as if \`-E --entry\` had been specified
  among other things.
* If neither restart nor entry function is provided, the program will exit with
  status \`0\` (success). If a function was provided, the program will exit
  after the function returns (if it returns), with status \`0\` if and only if
  the primary return value of result is generalized boolean true, and
  with status 1 if this value is \`NIL\`.
  See documentation for \`UIOP:RESTORE-IMAGE\` for details.

The current package can be controlled by option \`-p --package\` and its variant
\`-sp --system-package\` that also behaves like \`-s --system\`.
All forms passed to \`--eval\`, \`--init\`, \`--print\`, \`--write\`,
\`--final\`, \`--restart\`, \`--entry\`, etc., are read in the current package.
Files specified with \`-f --file --load\` are read in the current package.
Current means the package specified by the latest option \`-p --package\` or
\`-sp --system-package\` preceding the option being processed,
or \`cl-user\` if there was none.
Note that multiple \`-i --init\` or \`-F --final\` forms
may be evaluated consecutively after a package has been changed, and that
if one of these form itself modifies the package, or some other syntax control
mechanism such as the reader, it may adversely affect later forms in the same
category, but not those in other categories (if reached).


The following derived options work as if by a combination of simpler options:

* As mentioned above, option \`-sp --system-package\` combines \`--system\` and
  \`--package\` in one option, so that given the argument \`SYSTEM\`, the system
  is loaded as if by \`--system SYSTEM\` that creates a package \`SYSTEM\` that
  then becomes the current package.

* If option \`-DE --dispatch-entry\` is used, then the next argument must follow
  the format \`NAME/ENTRY\`, where \`NAME\` is a name that the program may be
  invoked as (the basename of the \`uiop:argv0\` argument), and \`ENTRY\` is
  a function to be invoked as if by \`--entry\` when that is the case.
  If the \`ENTRY\` is left out, function \`main\` in current package is used.
  Support for option \`-DE --dispatch-entry\` is delegated to a dispatch library,
  distributed with \`cl-launch\` but not part of \`cl-launch\` itself, by
  (1) registering a dependency on the dispatch library as if by
  \`--system cl-launch/dispatch\` (if not already)
  (2) if neither \`--restart\` nor \`--entry\` was specified yet, registering a
  default entry function as if by \`--entry cl-launch/dispatch:dispatch-entry\`.
  (3) registering a build-form that registers the dispatch entry as if by
  \`--eval '(cl-launch/dispatch:register-name/entry "NAME/ENTRY" :PACKAGE)'\`
  where \`PACKAGE\` is the current package.
  See the documentation of said library for further details.

* If option \`-Ds --dispatch-system\` is used with \`SYSTEM\` as its argument,
  it is as if option \`-s --system\` had been used with the same argument,
  followed by option \`-DE --dispatch-entry\` for the basename of the system
  (last \`/\` (slash) separated component of the system name) and the function \`main\`
  in the package of the system, but without otherwise changing the current package.

* If option \`-sm --system-main\` is used with \`SYSTEM\` as its argument,
  it is as if option \`-s --system\` had been used with the same argument,
  followed by option \`-E --entry\` with the \`main\` function
  in the package of the system, but without otherwise changing the current package.


General note on \`cl-launch\` invocation:
options are processed from left to right;
usually, repeated options accumulate their effects,
with the earlier instances taking effect before latter instances.
In case of conflicting or redundant options, the latter override the former.

\`cl-launch\` defines a package \`cl-launch\` that exports the following symbol:
   \`compile-and-load-file\`
Runtime functionality formerly provided by \`cl-launch\`
is now provided by \`UIOP\`, the portability layer provided by \`ASDF3\`.
See below section *cl-launch runtime API*.

When the first non-recognized option is a filename, \`cl-launch\` will try to
load this filename as a script, as if by \`--load\`,
then execute it immediately as if by \`--execute --\`,
with the rest of the command line passed as arguments.
The file name may not start with the character \`-\` or a \`(\` ---
To use a file with one of these (or something unknown) as a first character,
prepend \`./\` to the filename. Note that it is a security risk to let
adversaries control the names of files passed to cl-launch or other commands.

When option \`--execute\` is specified, the specified software is executed.
Command-line arguments may be given to software being executed by putting
them after a special marker \`--\`, that ends \`cl-launch\` option processing.

When option \`--output FILE\` is used, code will be generated
into the specified \`FILE\`. The output file itself
will be created atomically from complete generated contents
and may thus have the same pathname as the input file.
The restart function and init forms will not be evaluated, but kept for
when the output file is executed.
If \`-\` (after quoting) is specified, then the standard output is used.
If \`!\` (after quoting) is specified, then option \`--execute\` is assumed.

When no \`--output\` file is specified,
option \`--execute\` is implicitly assumed.
The last \`--output\` or \`--execute\` option
takes precedence over the previous ones.

If only one argument exists and it doesn't start with \`-\`
then the argument is considered as if given to option \`-ip\`,
to be evaluated and printed immediately.


The \`ASDF3\` source-registry configuration can be overridden with option
\`--source-registry SOURCE_REGISTRY\`. The provided configuration will take
priority over anything provided by the environment or configuration files,
though it may inherit from them as usual. See the \`ASDF3\` manual about that.


Options \`-l --lisp\` and \`-w --wrap\` may be used to control the way that
a Common Lisp implementation is found when the software is run.
Option \`-l --lisp\` specifies the list of implementations to try to use;
the list is whitespace-separated, and consists in
nicknames recognized by \`cl-launch\`.
Option \`-w --wrap\` supplies arbitrary code to be evaluated
by the shell wrapper, after it has read its configuration
and defined its internal functions, but before it tries
to find and run a Lisp implementation. Such wrapper code is typically used to
modify the variables that control the run-time behaviour of generated scripts,
as documented below. Use of other internals of \`cl-launch\` is possible,
but not supported, which means that it is your responsibility to keep a copy
of the specific version of cl-launch with which your code works and to
update your code if you later make an upgrade to an incompatible \`cl-launch\`.
For instance, \`--lisp "foo bar"\` is equivalent
to \`--wrap 'LISPS="foo bar"'\`.
See below the documentation section on *Lisp implementation invocation*.


Option \`--no-include\` specifies that cl-launch should generate a standalone
script that includes the configuration, shell wrapper, Lisp header, and
user-provided Lisp code (from \`--file\`). If you can rely on the presence of
a recent Lisp implementation that provides \`ASDF\`, then the script is pretty
much standalone indeed and may be moved around the filesystem and still used.
However the size of the output will be the size of the user Lisp code
plus about 36KiB.

Option \`--include PATH\` specifies that \`cl-launch\` should generate
a very small script (typically under 1KiB) that when run
will read the \`cl-launch\` shell wrapper and Lisp header
from a specified installation directory \`PATH\`.
Also, if option \`--include\` is used, and
Lisp code is specified with \`--file\`
and an absolute pathname starting with \`/\` as opposed to a relative pathname
or to the standard input, then Lisp code will also be loaded from the specified
location at runtime rather than embedded into the script at generation time.
This option generates leaner scripts, but may not be applicable when
the very same script is to used in a variety of situations
that lack common coherent filesystem management.

Which of \`--include\` or \`--no-include\` is the default
may depend on your cl-launch installation.
The version of \`cl-launch\` distributed by the author
uses \`--no-include\` by default, but
the version of \`cl-launch\` available in your operating system distribution may
rely on a well-managed include path (this is the case with debian for instance).
You may query the configuration of an instance of \`cl-launch\`
with option \`--version\`.

For instance, one may expect a debian version of cl-launch to use:
        \`/usr/share/common-lisp/source/cl-launch/\`
as a system-managed include path. One may also expect that Lisp implementations
managed by the system would come with \`cl-launch\` precompiled in Lisp images.
Since \`cl-launch\` provides feature \`:cl-launch\`,
and since the \`cl-launch\` Lisp header is conditionalized to not be read
with this feature, this would make \`cl-launch\` startup faster,
while still allowing non-system-managed Lisp implementations to run fine.

You may create an installation of cl-launch with such a command as:

        cl-launch --include /usr/share/common-lisp/source/cl-launch \\
                --lisp 'sbcl ccl clisp' \\
                --rc \\
                --output /usr/bin/cl-launch -B install

You can use command \`-B install_bin\` if you only want to configure cl-launch
(with a different default for \`--lisp\` but no \`--include\`, for instance),
and command \`-B install_path\` if you only want to create support files.
Note that the \`--backdoor\` option \`-B\` must come last in your invocation.


Option \`+R --no-rc\` specifies that \`cl-launch\` should not try to
read resource files \`/etc/cl-launchrc\` and \`~/.cl-launchrc\`.

Option \`-R --rc\` specifies that cl-launch should try to read resource
files \`/etc/cl-launchrc\` and \`~/.cl-launchrc\`.
These files are notably useful to define override the value of \`\$LISP\`
depending on \`\$SOFTWARE_SYSTEM\`. A shell function \`system_preferred_lisps\`
is provided so that your \`cl-launchrc\` might contain lines as follows:

        system_preferred_lisps stumpwm cmucl sbcl clisp
        system_preferred_lisps exscribe clisp cmucl sbcl

Beware that for the sake of parsing option \`--no-rc\`, the resource files
are run *after* options are processed, and that
any overriding of internal variables will thus preempt user-specified options.
A warning will be printed on the standard error output
when such an override happens.
Note that such overrides only happen at script-creation time.
A script created by \`cl-launch\`
will not try to read the \`cl-launch\` resource files.


Option \`+Q --no-quicklisp\` specifies that \`cl-launch\`
should not use \`quicklisp\`.
Option \`-Q --quicklisp\` specifies that \`cl-launch\` should use \`quicklisp\`.
Which is the default depends on your installation.
The default default is \`+Q\`.
Quicklisp is loaded from \`~/quicklisp/setup.lisp\` if available,
or else \`~/.quicklisp/setup.lisp\`.

Option \`-b --clbuild\` specifies that \`cl-launch\` should rely
on \`clbuild\` to find and invoke the Common Lisp implementation.
Option \`+b --no-clbuild\` specifies that \`cl-launch\` should not rely
on \`clbuild\` to find and invoke the Common Lisp implementation.
Which is the default depends on your installation.
The default default is \`+b\`.


Files generated by \`cl-launch\` are made of several well-identifiable sections.
These sections may thus be considered as distinct software, each available
under its own regime of intellectual property (if any). In case of an accident,
you may still retrieve the exact original code provided with option \`--file\`
by stripping the wrapper, as delimited by well-identified markers.
Search for the marker string \`"BEGINS HERE:"\`.
Everything after it is not \`cl-launch\`.
This can be done automatically with backdoor option \`-B extract_lisp_content\`.
\`cl-launch\` uses this functionality implicitly when embedding a file specified
with the option \`--file\`, so that you may process
a script previously generated by \`cl-launch\` and change the options
with which it wraps the embedded Lisp code into runnable software.

As an alternative, you may also upgrade a previously generated script to use
the current version of \`cl-launch\` while preserving
its original wrapping options with option \`--update\`.
In this case, software specification options are ignored.
Output options still apply. Specifying \`-\` (after quoting) as the file to
update means to read the contents to be read from the standard input.
This feature might not work with scripts generated by very early versions
of the \`cl-launch\` utility. It should work with versions later than 1.47.


Supported Lisp implementations
------------------------------

The implementations supported by current version of cl-launch are:

        abcl allegro ccl clisp cmucl ecl gcl lispworks sbcl scl xcl

Also defined are aliases:

        clozurecl gclcvs lisp openmcl

which are name variations for \`ccl\`, \`gcl\`, \`cmucl\` and \`ccl\`
again respectively.

Fully supported, including standalone executables:

    sbcl:  SBCL 1.2.2
    clisp:  GNU CLISP 2.49
    ecl:  ECL 13.5.1
    cmucl:  CMUCL 20D
    ccl:  ClozureCL 1.10
    lispworks:  LispWorks Professional 6.1.0  (no personal ed, banner)

Fully supported, but no standalone executables:

    gcl (GCL 2.7):  GCL 2.7.0 ansi mode  (get a very recent git checkout)
    allegro:  Allegro 9.0  (also used to work with 5)
    scl:  Scieneer CL 1.3.9

Incomplete support:

    abcl:  ABCL 1.3.1 (no image dumping support, but you may use abcl-jar)
    xcl:  XCL 0.0.0.291 (cannot dump an image) (get a recent checkout)


\`GCL\` is only supported in ANSI mode. \`cl-launch\` does export GCL_ANSI=t
in the hope that the \`gcl\` wrapper script does the right thing
as it does in Debian. Also \`ASDF3\` requires a very recent \`GCL 2.7\`.
Note that \`GCL\` seems to not be very actively maintained anymore.

There are some issues regarding standalone executables on \`CLISP\`.
See below in the section regarding *Standalone executables*.

\`LispWorks\` requires the Professional Edition; the Personal Edition isn't
supported as it won't let you either control the command line or dump images.
Dumped images will print a banner, unless you dump a standalone executable.
To dump an image, make sure you have a license file in your target directory
and/or to .../lispworks/lib/6-1-0-0/config/lwlicense
(or use a trampoline shell script to \`exec /path/to/lispworks "\$@"\`),
create a build script with:

       echo '(hcl:save-image "lispworks-console" :environment nil)' > si.lisp
       lispworks-6-1-0-x86-linux -siteinit - -init - -build si.lisp

LispWorks also requires that you have \`ASDF 3.1.2\` or later;
make sure you have it installed and configured in your source registry.
There is no standard name for a console-only variant of LispWorks;
older versions of cl-launch assume a default \`lispworks\`; since 4.1.2.1,
\`lispworks-console\` is assumed instead, to avoid conflicts. You can
control the name you use with the shell variable \`\$LISPWORKS\`, or you
can just leave \`lispworks-console\` in your path, and use a symlink, copy,
shell alias or trivial wrapper script to enable your favorite shorter name
\`lispworks\`, \`lw\`, \`lwcon\`, \`lw-console\`, etc.

Similarly, a mlisp image for allegro can be created as follows:

        alisp -e '(progn
                   (build-lisp-image "sys:mlisp.dxl"
                    :case-mode :case-sensitive-lower
                    :include-ide nil :restart-app-function nil)
                   (when (probe-file "sys:mlisp") (delete-file "sys:mlisp"))
                   (sys:copy-file "sys:alisp" "sys:mlisp"))'

Additionally, \`cl-launch\` supports the use of \`clbuild\` as a wrapper
to invoke the Lisp implementation, with the \`--clbuild\` option.


Supported shells
----------------

\`cl-launch\` was tested with all of
\`posh\` 0.4.7, \`bash\` 2.05, \`bash\` 3.1, \`zsh\` 4.3.2,
\`dash\` 0.5.3 and \`busybox\` 1.01 \`ash\`.


Lisp implementation invocation
------------------------------

When a \`cl-launch\` generated script is invoked,
the \`cl-launch\` shell wrapper will try to execute the Lisp code
with the first Common Lisp implementation it finds in a given list,
which can be specified through option \`--lisp\`.
The runtime behaviour of the \`cl-launch\` shell wrapper
is very configurable through a series of environment variables.
These variables can be controlled by the user
by exporting them in his environment, or
they can be restricted at the time of script generation
by using cl-launch option \`--wrap\`.

If variable \`LISP\` is defined, the shell wrapper will first try
the implementation named by variable \`LISP\`. If that fails,
it will try the list of implementations provided at script generation time.
The list of implementations generated will be
the argument to option \`--lisp\` if specified.
Otherwise, \`cl-launch\` will supply its default value.
This default value for the current instance of \`cl-launch\` is:

        $DEFAULT_LISPS

This \`LISP\` selection only happens at system preparation time.
If you dump an image then the script will always use the Lisp implementation
for which an image was dumped.
If you don't then the user may override the implementation.


Note that these are nicknames built into the \`cl-launch\` shell wrapper,
and not necessarily names of actual binary. You may control the mapping of
implementation nickname to actual binary pathname to call with an environment
variable. For a given implementation nickname, the environment variable will be
the capitalization of the given nickname.
Hence, variable \`\$SBCL\` controls where to look for the \`sbcl\` implementation,
and variable \`\$CMUCL\` controls where to look for the \`cmucl\` implementation.
If a binary is found with a matching pathname (using the standard unix \`\$PATH\`
as required), then said implementation will be used, using proper command line
options, that may be overridden with an environment variable similar to the previous
but with \`_OPTIONS\` appended to its name.
Hence, \`\$CMUCL_OPTIONS\` for \`cmucl\`, \`\$CLISP_OPTIONS\` for \`clisp\`, etc.
Sensible defaults are provided for each implementation, so as to execute the
software in non-interactive mode, with debugger disabled, without reading
user-specific configuration files, etc.

If you want to insist on using a given implementation with given options,
you may use option \`--lisp\` and \`--wrap\`, as follows:

    --lisp 'sbcl clisp' --wrap '
        LISP= # do not allow the user to specify his implementation
        SBCL=/usr/bin/sbcl # not any experimental thing by the user
        SBCL_OPTIONS="--noinform --sysinit /dev/null --userinit /dev/null \\
        --disable-debugger" # predictable Lisp state
        CLISP=/usr/bin/clisp # fall back on machines that lack SBCL
        CLISP_OPTIONS=" -norc --quiet --quiet"
        # configure ASDF:
        CL_SOURCE_REGISTRY=/usr/local/share/common-lisp/source//:
        # assuming precompiled fasls there:
        ASDF_OUTPUT_TRANSLATIONS=/my/cl/src:/my/fasl/cache:
        '

If you dump an image, you need not unset the \`LISP\` variable, but you
might still want to override any user-specified \`SBCL\` and \`SBCL_OPTIONS\`
(or corresponding variables for your selected implementation) from what
the user may specify.

Note that you can use option \`--wrap "\$(cat your_script)"\`
to embed into your program a full fledged script from a file.
Your script may do arbitrary computations before the shell wrapper is run.
It may make some consistency checks and abort before to run Lisp.
Or it may analyze invocation arguments and make according adjustments
to Lisp implementation options. This can be useful for setting options
that cannot be set from the Lisp code, such the path to a runtime image,
interactive or non-interactive execution, size of heaps,
locale settings for source file encoding, etc.

Reading the source code of \`cl-launch\` can be completely crazy.
You may have great fun understanding why things are how they are
and adding features without breaking anything! However,
adding support for a new CL implementation should be straightforward enough:
just search the sources for \`clisp\` or \`sbcl\` and mimic what I did for them.
Be sure to send me what will get your favorite Lisp flavor of the month rolling.


Limited clbuild support
-----------------------

\`cl-launch\` 2.12 and later support using \`clbuild\` as a wrapper
to configure your Lisp implementation, with option \`--clbuild\`
(which can be disabled with option \`--no-clbuild\` if it was enabled by default
in your \`cl-launch\` installation).

Note that when you use \`clbuild\`, you can no longer override implementation
options with say \`SBCL_OPTIONS\`, as clbuild takes care of the options for you.
Any implementation banner will not be removed unless you instruct clbuild
to do so. Also, you cannot use clbuild with a non-executable image different
from \`clbuild\`'s, which precludes image dumping with \`cmucl\` or \`allegro\`
(\`allegro\` could probably be updated, but I don't have a recent licence
to test and develop).

\`clbuild\` support is not fully tested at this point. Please report any bug.


Simple cl-launch scripts
------------------------

In simple cases, you may create a Common Lisp shell script with \`cl-launch\`
without a script generation step, just because you'll spend a lot of time
editing the script and distributing it, and little time waiting for script
startup time anyway. This notably is a good idea if you're not spawning many
instances of the same version of a script on a given computer. If that's
what you want, you may use \`cl-launch\` as a script interpret the following way
(stripping leading spaces):

    #!/path/to/cl-launch ...options...

For instance, you may write the following script (stripping leading spaces):

    #!/usr/bin/cl --entry main
    (defun main (argv)
      (format t "Hello, World!~%~S~%" argv))

On a recent Linux kernel, the options may include spaces, parentheses, etc.,
provided they are quoted as in a shell script.
Also, using \`-X\` as your very first option and \`--\` as your last
will ensure that the script works even if its name starts with
a \`(\` or a \`-\`, in addition to working with older versions of \`cl-launch\`.

Note however that Darwin (MacOS X) and other BSD kernels or old Linux kernels
don't like the \`#!\` interpreter to itself be interpreted.
On these operating system kernels, the system administrator must
compile and install a small shim written in C, \`cl-shim.c\`,
that will handle the proper script invocation.

Most kernels have restrictions on how they handle arguments to a \`#!\` script,
that prevent e.g. using \`/usr/bin/env\` as a trampoline;
however, you may use the fully portable solution as follows,
where the \`":" ;\` ensures that the script should remain valid
bilingual shell and Lisp code:

    #!/bin/sh
    ":" ; exec cl-launch -X -sp my-package -E main -- "\$0" \${1+"\$@"} || exit

(Actually \`"\$@"\` instead of \`\${1+"\$@"}\` should work just fine,
unless you have an antique shell.)

Note that if you don't need Lisp code to be loaded from your script,
with everything happening in the build specification, then you may instead
use a simple \`#!/bin/sh\` shell script from which you:

    exec /path/to/cl-launch -x ... -- "\$@".

Also, in case you can't rely on \`cl-launch\` being at a fixed path,
or if your shell and/or kernel combination doesn't support using \`cl-launch\`
as a script interpreter, then you may instead start your script
with the following lines:

    #!/bin/sh
    ":" ; exec cl-launch -X -- "\$0" "\$@" || exit
    (format t "It works!~%")

Note that a mainline Linux kernel only supports the recursive \`#!\`
implicit in \`#!/usr/bin/cl-launch\` since 2.6.27.9.


Dumping images
--------------

You can dump an image (for static compilation and fast startup) with option
\`--dump IMAGE\` where \`IMAGE\` specifies
the path where the image will be dumped.

If you use option \`--include PATH\` then the image will be loaded back from
that specified directory instead of the directory where you dumped it.
This is useful if you're preparing a script to be installed at another place
maybe on another computer.

This option is currently supported on all CL implementations available
with \`cl-launch\`.

As a limitation, \`LispWorks\` will print a banner on standard output,
unless you use the standalone executable option below.

As another limitation, \`ECL\` will not be able to dump an image when running
from a previously dumped image (with \`--image\`). This is because of the
link model of ECL, whereby you'd need to be able to locate which object files
were used in linking the original image, keep track of these files,
and prepend the list of them to to the object files linked into the dump.
This is not conceptually impossible and patches are welcome.
However, we hope to support that someday with a real build system
that does it for you, such as XCVB.



Standalone executables
----------------------

You can create standalone executables with the option \`--dump '!'\`
(or by giving a \`--dump\` argument identical to the \`--output\` argument).

This option is currently only supported with
\`SBCL\`, \`ECL\`, \`CLISP\`, \`CMUCL\`, \`CCL\` and \`LispWorks\` Professional.
Moreover \`CLISP\` has the issues below.

\`CLISP\` standalone executables will react magically if invoked with options
such as \`--clisp-help\` or \`--clisp-x '(sys::main-loop)'\`.
That's a pretty far-fetched thing to hit by mistake, and
the \`CLISP\` maintainers consider it a feature (I don't).
Don't use such executables as \`setuid\`, and don't let untrusted users
control arguments given to such executables that are run with extra privileges.


cl-launch runtime API
---------------------

\`cl-launch\` provides the following Lisp functions:

Function \`cl-launch:compile-and-load-file\` takes as an argument
a source pathname designator, and keyword arguments
\`force-recompile\` (default \`NIL\`) and \`verbose\` (default \`NIL\`).
It will arrange to compile the specified source file if it is
explicitly requested, or if the file doesn't exist,
or if the fasl is not up-to-date.
It will compile and load with the specified verbosity.
It will take use \`uiop:compile-file-pathname*\` to determine the fasl pathname.

The following variables and functions previously provided by \`cl-launch\`
have the following replacement from \`ASDF\` and \`UIOP\`:

Variable \`cl-launch:*arguments*\`
is replaced by \`uiop:*command-line-arguments*\`.

Function \`cl-launch:getenv\` is replaced by \`uiop:getenv\`.

Function \`cl-launch:load-system\` is replaced by \`asdf:load-system\`.

Function \`cl-launch:quit\` is replaced by \`uiop:quit\`
(beware: the lambda-list is slightly different).

Additionally, environment variables \`CL_LAUNCH_PID\` and \`CL_LAUNCH_FILE\`
will be set to the process ID and the script invocation filename respectively.


Verbose output mode
-------------------

If the shell variable \`CL_LAUNCH_VERBOSE\` is exported and non-\`nil\`,
then \`cl-launch\` and the scripts it generates will produce
an abundance of output, display such things as the Lisp invocation command,
compiling and loading files with \`:verbose t\` and \`:print t\`, etc.
This is only useful for debugging \`cl-launch\` and/or your build process.
Option \`--verbose\` sets this variable, whereas option \`--quiet\` resets it.


Makefile examples
-----------------

    ### Automatically download of the current version of cl-launch if not present
    cl-launch.sh:
            wget -O cl-launch.sh ${CL_LAUNCH_URL}
            chmod a+x cl-launch.sh

    ### Making a shell script executable from a simple Lisp file named foo.lisp
    foo.sh: cl-launch.sh foo.lisp
            ./cl-launch.sh --output foo.sh --file foo.lisp

    ### A more complex example using all options.
    run-foo.sh: cl-launch.sh preamble.lisp
            ./cl-launch.sh --output run-foo.sh \\
            --file preamble.lisp --system foo \\
            --init "(foo:main uiop:*command-line-arguments*)" \\
            --source-registry \${PREFIX}/cl-foo/systems: \\
            --lisp "ccl sbcl" --wrap 'SBCL=/usr/local/bin/sbcl-no-unicode' \\
            --no-include

    ### An example with horrible nested makefile, shell and Lisp quoting
    hello:
            opera=wORlD ; ./cl-launch.sh --execute --init \\
            "(format t \\"~25R~A~A~%\\" 6873049 #\\\\space '\$\$opera)"


Caveat Lispor
-------------

\`cl-launch\` begins evaluation of your Lisp software
in the \`cl-user\` package, or whichever package you specify.
By the time your initialization forms are evaluated,
the package may or may not have changed,
depending on the fine-grained semantics of \`load\`.
Be sure to use \`in-package\` if these things matter.
If you change the readtable, even weirder things may happen.

There are lots of ways of making mistakes by improperly quoting things when
you write shell commands. \`cl-launch\` does the right thing,
but you still must be careful with the nested quoting mechanisms
of \`make\`, shell, and Lisp.

Here is a simple example use of cl-launch to quickly compare the result of
a same computation on a variety of systems:

    for l in sbcl cmucl clisp gcl ccl ; do
      ./cl-launch.sh --lisp \$l --execute --init \\
        '(format t "'\$l' ~A~%" most-positive-fixnum)' ; done

Internally, \`cl-launch\` includes many self-test functions.
You may for instance try (from a directory where it may create junk):

    ./cl-launch.sh -l 'sbcl cmucl clisp gclcvs' -B tests

Share and Enjoy!
EOF
}

show_help () {
  print_help_header
  echo
  print_help
  echo
  print_help_footer
  exit "${1:-0}"
}
show_more_help () {
  print_help_header
  echo
  print_help
  echo
  print_more_help
  echo
  print_help_footer
  exit "${1:-0}"
}
error_help () {
  show_help "${1:-2}" >& 2
}
show_version () {
  echo "cl-launch ${CL_LAUNCH_VERSION}

Supported implementations:
    sbcl, cmucl (lisp), clisp, ecl, ccl (openmcl), abcl, mkcl,
    xcl, gcl (gclcvs), allegro (alisp), lispworks, scl

Local defaults for generated scripts:
  will search in this order these supported implementations:
      ${DEFAULT_LISPS}"
  if [ -z "$DEFAULT_INCLUDE_PATH" ] ; then
    echo "\
  will generate self-contained scripts using option --no-include by default"
  else
    echo "\
  will generate scripts by default with runtime dependencies using option
    --include ${DEFAULT_INCLUDE_PATH}"
  fi
  if [ -n "$DEFAULT_USE_CL_LAUNCHRC" ] ; then
    echo "\
  will use /etc/cl-launchrc and ~/.cl-launchrc by default"
  else
    echo "\
  will not use /etc/cl-launchrc and ~/.cl-launchrc by default"
  fi
  if [ -z "$DEFAULT_USE_CLBUILD" ] ; then
    echo "\
  will generate scripts that do not use clbuild by default"
  else
    echo "\
  will generate scripts that use clbuild by default"
  fi
  if [ -z "$DEFAULT_USE_QUICKLISP" ] ; then
    echo "\
  will generate scripts that do not use quicklisp by default"
  else
    echo "\
  will generate scripts that use quicklisp by default"
  fi
  echo
  exit
}

### Generic debugging library excerpted from ~fare/etc/zsh/fun.*

print_basic_functions () {
  cat <<'EOF'
ECHOn () { printf '%s' "$*" ;}
simple_term_p () {
  case "$1" in *[!a-zA-Z0-9-+_,.:=%/]*) return 1 ;; *) return 0 ;; esac
}
if [ -n "$BASH_VERSION$ZSH_VERSION" ] ; then
  kwote0 () { a="${1//\\/\\\\}" ; a="${a//\`/\\\`}" ; a="${a//\$/\\\$}" ; printf %s "${a//\"/\\\"}" ;}
else
  kwote0 () { ECHOn "$1" | sed -e "s/\([\\\\\"\$\`]\)/\\\\\\1/g" ;}
fi
kwote () { if simple_term_p "$1" ; then ECHOn "$1" ; else kwote0 "$1" ; fi ;}
load_form_0 () { echo "(cl:load $1 :verbose nil :print nil)" ;}
load_form () { load_form_0 "\"$(kwote "$1")\"" ;}
ECHO () { printf '%s\n' "$*" ;}
DBG () { ECHO "$*" >& 2 ;}
abort () { ERR="$1" ; shift ; DBG "$*" ; exit "$ERR" ;}
ABORT () { abort 42 "$*" ;}
EOF
}

eval "$(print_basic_functions)"

kwote1 () { if simple_term_p "$1" ; then ECHOn "$1"
  else ECHOn "\"$(kwote0 "$1")\"" ; fi ;}
SHOW () { ( set +x
  k="" ; for i ; do ECHOn "$k" ; kwote1 "$i" ; k=" " ; done ; echo
) }
XDO () { SHOW "$@" >&2 ; "$@" ;}
DO () { SHOW "$@" ; "$@" ;}
EVAL () { ECHO "$*" ; eval "$*" ;}
fullpath () {
 # If we were sure readlink is here, we could: for i ; do readlink -f "$i" ; done
 for i ; do case "$i" in /*) ECHO "$i" ;; *) ECHO "$PWD/$i" ;; esac ; done
}
print_var () {
  for var ; do eval "ECHO \"$var=\$(kwote1 \"\${$var}\")\"" ; done ;}
create_file () {
  MOD="$1" OUT="$2" ; shift 2; TMPFILE="$OUT.tmp$$~"
  if "${@:-cat}" > "$TMPFILE" &&
     chmod "$MOD" "$TMPFILE" &&
     mv -f "$TMPFILE" "$OUT" ;
  then return 0 ; else rm -f "$TMPFILE" ; return 1 ; fi
}

### Process options
OPTION () { process_options "$@" ;}
process_options () {
  while [ $# -gt 0 ] ; do
    x="$1" ; shift
    case "$x" in
      -h|"-?"|--help)
        show_help ;;
      -H|--more-help)
        show_more_help ;;
      -V|--version)
        show_version ;;
      -v|--verbose)
        export CL_LAUNCH_VERBOSE=t ;;
      -q|--quiet)
        unset CL_LAUNCH_VERBOSE ;;
      -e|--eval)
        add_build_form "(:eval \"(cl:in-package :$PACKAGE)$(kwote "$1")\")" ; shift ;;
      -L|--load)
        add_build_form "(:load \"$(kwote "$1")\" :$PACKAGE)" ; shift ;;
      -f|--file)
        add_build_form "(:load t :$PACKAGE)" ; set_lisp_content "$1" ; shift ;;
      -s|--system|--load-system)
        add_build_form "(:load-system \"$(kwote "$1")\")" ; shift ;;
      --require)
        add_build_form "(:require \"$(kwote "$1")\")" ; shift ;;
      -F|--final)
        add_final_form "$1" ; shift ;;
      -i|--init)
        add_init_form "$1" ; shift ;;
      -ip|--print)
        add_init_form "(princ(progn $1))(terpri)" ; shift ;;
      -iw|--write)
        add_init_form "(write(progn $1))(terpri)" ; shift ;;
      -p|--package)
        in_package "$1" ; shift ;;
      -sp|--system-package)
        add_build_form "(:load-system \"$1\")"
        in_package "$1" ; shift ;;
      "("*)
        add_init_form "(princ(progn $x))(terpri)" ;;
      -p|-pc|+p)
        ABORT "option $x is not supported anymore." \
                "Use option -S instead." ;;
      --path|--path-current|--no-path)
        ABORT "option $x is not supported anymore." \
                "Use option --source-registry instead." ;;
      -S|--source-registry)
        SOURCE_REGISTRY="$1" ; shift ;;
      -l|--lisp)
        LISPS="$1" ; shift ;;
      -w|--wrap)
        WRAPPER_CODE="$1" ; shift ;;
      -I|--include)
        INCLUDE_PATH="$1" ; shift ;;
      +I|--no-include)
        INCLUDE_PATH="" ;;
      -R|--rc)
        USE_CL_LAUNCHRC=t ;;
      +R|--no-rc)
        USE_CL_LAUNCHRC= ;;
      -b|--clbuild)
        USE_CLBUILD=t ;;
      +b|--no-clbuild)
        USE_CLBUILD= ;;
      -Q|--quicklisp)
        USE_QUICKLISP=t ;;
      +Q|--no-quicklisp)
        USE_QUICKLISP= ;;
      -o|--output)
        OUTPUT_FILE="$1" ; shift ;;
      -x|--execute)
        OUTPUT_FILE="!" ;;
      -u|--update)
       UPDATE="$1" ; shift ;;
      -m|--image)
        LOAD_IMAGE="$1" ; shift ;;
      -d|--dump)
        DUMP="$1" ; shift ;;
      -r|--restart)
        set_restart "$1" ; shift ;;
      -E|--entry)
        set_restart "(lambda()($1 uiop:*command-line-arguments*))" ; shift ;;
      -DE|--dispatch-entry)
        add_dispatch_entry "$1" "$PACKAGE"
        shift ;;
      -sm|--system-main)
        add_build_form "(:load-system \"$(kwote "$1")\")"
        set_entry "$1::main" ; shift ;;
      -Ds|--dispatch-system)
        sys="$(kwote "$1")"
        add_build_form "(:load-system \"$sys\")"
        add_dispatch_entry "$(basename $sys)" "$sys" ; shift ;;
      -B|--backdoor)
        "$@" ; exit ;;
      --)
        if [ -n "${IS_X_SCRIPT}" ] ; then
          add_build_form "(:load \"$(kwote "$1")\" :cl-user)"
          export __CL_ARGV0="$1"
          shift
        fi
        if [ "x${OUTPUT_FILE}" = "x!" ] ; then
          do_it "$@"
        else
          ABORT "Extra arguments given but not in --execute mode"
        fi
        ;;
      -X) OPTION -x
        IS_X_SCRIPT=y
        ;;
      -X' '*)
        # DBG "Working around sh script script limitation..."
        # The below gets the script arguments from the kernel-given argument:
        #       OPTS="$x" ; eval "OPTION $OPTS \"\$@\""
        # Unix kernels traditionally lump everything after the interpreter name
        # from the #! line up to 127 characters into one (optional) argument,
        # as defined in linux/{fs/binfmt_script.c,include/linux/binfmts.h}.
        # If we want to allow for a longer in-script command line argument,
        # and we do if we want to accommodate for inline Lisp code using -i
        # then we'd need to go fetch the full line and parse it. Here it is:
        OPTS="$(get_hashbang_arguments "$1")"
        eval "OPTION $OPTS \"\$@\""
        ABORT "The cl-launch script $1 failed to use -X ... --"
        ;;
       -*)
        # Directly handle arguments in a #! script
        if [ -f "$1" ] ; then
          OPTS="$(get_hashbang_arguments "$1")"
          OPTx="$(stringbefore "${#x}" "$OPTS")"
          if [ "x$x" = "x$OPTx" ] ; then
            export __CL_ARGV0="$2"
            eval "OPTION $OPTS \"\$@\""
          fi
        fi
        DBG "Invalid command line argument '$x'" ; mini_help_abort ;;
       *)
        unset IS_X_SCRIPT
        export __CL_ARGV0="$x"
        OPTION --load "$x" --execute -- "$@" ;;
    esac
  done
}
in_package () {
  PACKAGE="$1"
}
set_restart () {
  RESTART="$1" RESTART_PACKAGE="$PACKAGE"
}
set_entry () {
  set_restart "(cl:lambda()($1 uiop:*command-line-arguments*))"
}
add_dispatch_entry () {
  if [ -z "$DISPATCH_ENTRY_P" ] ; then
    add_build_form "(:load-system \"cl-launch/dispatch\")"
    DISPATCH_ENTRY_P=t
  fi
  if [ -z "$RESTART" ] ; then
    set_entry "cl-launch/dispatch:dispatch-entry"
  fi
  add_build_form "(:eval \"$(kwote "(cl-launch/dispatch:register-name/entry \"$(kwote "$1")\" :$2)")\")"
}
add_build_form () {
        SOFTWARE_BUILD_FORMS="$SOFTWARE_BUILD_FORMS${SOFTWARE_BUILD_FORMS+
}$1"
}
add_init_form () {
  if ! [ "${INIT_PACKAGE}" = "$PACKAGE" ] ; then
    package_form="(cl:in-package :$PACKAGE)"
    INIT_PACKAGE="$PACKAGE"
  else
    package_form=""
  fi
        SOFTWARE_INIT_FORMS="$SOFTWARE_INIT_FORMS${SOFTWARE_INIT_FORMS+
}${package_form}$1"
}
add_final_form () {
  if ! [ "${FINAL_PACKAGE}" = "$PACKAGE" ] ; then
    package_form="(cl:in-package :$PACKAGE)"
    FINAL_PACKAGE="$PACKAGE"
  else
    package_form=""
  fi
        SOFTWARE_FINAL_FORMS="$SOFTWARE_FINAL_FORMS${SOFTWARE_FINAL_FORMS+
}${package_form}$1"
}
set_lisp_content () {
  if [ -z "$1" ] ; then
    ABORT "Empty argument after -f --file"
  elif [ -n "$LISP_CONTENT" ] ; then
    ABORT "You may only use option -f --file once"
  else
    LISP_CONTENT="$1"
  fi
}
if [ -n "$BASH_VERSION$ZSH_VERSION" ] ; then
  stringbefore () { ECHOn "${2:0:$1}" ;}
  stringafter () { ECHOn "${2:$1}" ;}
else
  stringbefore () { ECHOn "$2" | cut -c-"$1" ;}
  stringafter () { ECHOn "$2" | cut -c"$1"- ;}
fi
get_hashbang_arguments () {
 stringafter 2 "$(read LINE < "$1" ; ECHOn "$LINE")" |
 { read INTERP ARGUMENTS ; ECHOn "$ARGUMENTS" ;}
}
mini_help_abort () {
  DBG "$HELP_HEADER

For help, invoke script with help argument:
        $PROG -h" ; ABORT
}

### Do the job
guess_defaults () {
  if [ -n "$UPDATE" ] ; then
    : "${OUTPUT_FILE:=$UPDATE}"
  fi
}
# Configuration
system_preferred_lisps () {
  if [ "x${SOFTWARE_SYSTEM}" = "x$1" ] ; then
    shift
    LISPS="$*"
    DBG "User configuration for system ${SOFTWARE_SYSTEM} overrides LISPS with $(kwote1 "$LISPS")"
  fi
}
try_resource_file () {
  if [ -f "$1" ] ; then
    . "$1"
  fi
}
try_resource_files () {
  if [ -n "$USE_CL_LAUNCHRC" ] ; then
    try_resource_file /etc/cl-launchrc
    try_resource_file "$HOME/.cl-launchrc"
  fi
}
print_configuration () {
  print_var \
        LISP_CONTENT SOFTWARE_SYSTEM SOFTWARE_INIT_FORMS SOFTWARE_FINAL_FORMS \
        SOURCE_REGISTRY INCLUDE_PATH LISPS WRAPPER_CODE \
        DUMP RESTART IMAGE_BASE IMAGE_DIR IMAGE \
        $EXTRA_CONFIG_VARIABLES
}
include_configuration () {
  if [ -n "$UPDATE" ] ; then
    extract_configuration
    ECHO "$CONFIGURATION"
    eval "$CONFIGURATION"
  else
    extract_configuration
    print_configuration
  fi
}
ensure_configuration () {
  extract_configuration
  if [ -n "$UPDATE" ] ; then
    eval "$CONFIGURATION"
    adjust_configuration
  fi
}
adjust_configuration () {
  : INCLUDE_PATH="$INCLUDE_PATH" LISP_CONTENT="$LISP_CONTENT"
  if [ -n "$INCLUDE_PATH" ] ; then
    AUTHOR_NOTE= SHORT_LICENSE= LICENSE_COMMENT=
  fi
}
include_license () {
  if [ -n "$DISCLAIMER" ] ; then
    l=
    for i in "$DISCLAIMER" "$AUTHOR_NOTE" "$SHORT_LICENSE" "$LICENSE_COMMENT"
    do l="$l$i${i:+#
}" ;  done
  ECHOn "$l"
  fi
  hide_license
}
hide_license () {
  DISCLAIMER= AUTHOR_NOTE= SHORT_LICENSE= LICENSE_COMMENT= CONTENT_DISCLAIMER=
}
include_lisp_header () {
  if [ -z "$INCLUDE_PATH" ] ; then
    print_lisp_header
  else
    echo "#-cl-launch"
    load_form "$INCLUDE_PATH/launcher.lisp"
  fi
}
LAUNCH_FUN=cl-launch::run
print_lisp_launch () {
  ECHOn "($LAUNCH_FUN"
  if [ -n "${SOURCE_REGISTRY}" ] ; then
    ECHOn " :source-registry \"$(kwote "$SOURCE_REGISTRY")\""
  fi
  if [ -n "${USE_QUICKLISP}" ] ; then
    ECHOn " :quicklisp t"
  fi
  if [ -n "${SOFTWARE_BUILD_FORMS}" ] ; then
    ECHOn " :build '(${SOFTWARE_BUILD_FORMS})"
  fi
  if [ -n "${SOFTWARE_FINAL_FORMS}" ] ; then
    ECHOn " :final \"$(kwote "${SOFTWARE_FINAL_FORMS}")\""
  fi
  if [ -n "${SOFTWARE_INIT_FORMS}" ] ; then
    ECHOn " :init \"$(kwote "${SOFTWARE_INIT_FORMS}")\""
  fi
  if [ -n "${NO_QUIT}" ] ; then
    ECHOn " :quit nil"
  fi
  if [ -n "${DUMP}" ] ; then
    ECHOn " :dump \"$(kwote "${DUMP}")\""
  fi
  if [ -n "${RESTART}" ] ; then
    ECHOn " :restart '(\"$(kwote "${RESTART}")\" . :${RESTART_PACKAGE})"
  fi
  ECHOn ")"
}
print_lisp_initialization () {
  echo "#-cl-launched"
  print_lisp_launch
}
print_lisp_content () {
  ECHO "$CONTENT_DISCLAIMER"
  ECHO "$CONTENT_BEGIN_MARKER"
  extract_lisp_content
}
include_lisp_content () {
  if [ -n "$LISP_CONTENT" ] ; then print_lisp_content ; fi
}
include_shell_wrapper () {
  ECHO "$BASIC_ENV_CODE"
  if [ -z "$INCLUDE_PATH" ] ; then
    print_shell_wrapper
  else
    ECHO ". $(kwote1 "$INCLUDE_PATH/wrapper.sh")"
  fi
}
include_script_configuration_and_headers () {
  ECHOn "\
#!/bin/sh
#| CL-LAUNCH ${CL_LAUNCH_VERSION} CONFIGURATION
" ; include_configuration ; ECHOn "\
# END OF CL-LAUNCH CONFIGURATION

# This file was generated by cl-launch ${CL_LAUNCH_VERSION}
" ; include_license
}
make_loader () {
 include_script_configuration_and_headers
 include_shell_wrapper
 ECHOn '

launch_self "$@"
ABORT
# |#
' ; include_lisp_stuff
}
include_lisp_stuff () {
  include_lisp_header ; ECHOn '

;;;; CL-LAUNCH LISP INITIALIZATION CODE

' ; print_lisp_initialization ; ECHOn '

;;;; END OF CL-LAUNCH LISP INITIALIZATION CODE

' ; include_lisp_content
}
READ () {
  if [ $UNREAD_DEPTH = 0 ] ; then
    read -r LINE
  elif [ $UNREAD_DEPTH = 1 ] ; then
    UNREAD_DEPTH=0
    LINE="$LINE1"
  elif [ $UNREAD_DEPTH = 2 ] ; then
    UNREAD_DEPTH=1
    LINE="$LINE1"
    LINE1="$LINE2"
  else
    ABORT "error: UNREAD_DEPTH=$UNREAD_DEPTH"
  fi
}
UNREAD () {
  if [ $UNREAD_DEPTH = 0 ] ; then
    UNREAD_DEPTH=1
    LINE1="$1"
  elif [ $UNREAD_DEPTH = 1 ] ; then
    UNREAD_DEPTH=2
    LINE2="$LINE1"
    LINE1="$1"
  else
    ABORT "error: UNREAD_DEPTH=$UNREAD_DEPTH"
  fi
}
extract_configuration () {
  TRIED_CONFIGURATION=t
  CONFIGURATION=
  READ || return
  : "READ => $LINE"
  L1="#!/bin/sh"
  case "$LINE" in
    "$L1") : "read the SHEBANG" ;;
    *) : "Not a shell script" ; UNREAD "$LINE" ; return 2 ;;
  esac
  if ! READ ; then UNREAD "$L1" ; return 2 ; fi
  : "READ => $LINE"
  case "$LINE" in
    "#| CL-LAUNCH"*" CONFIGURATION") : "read the CL comment start" ;;
    *) : "Not a cl-launch script" ; UNREAD "$LINE" ; UNREAD "$L1" ; return 2 ;;
  esac
  while READ &&
    #: "READ => $LINE" &&
    case "$LINE" in
      "# END OF CL-LAUNCH CONFIGURATION") ! : ;;
      *) : ;;
    esac
  do CONFIGURATION="$CONFIGURATION${CONFIGURATION:+
}$LINE" ; done
  HAS_CONFIGURATION=t
}
extract_lisp_content () {
  if [ -z "$TRIED_CONFIGURATION" ] ; then
    extract_configuration
  fi
  if [ -n "$HAS_CONFIGURATION" ] ; then
    skip_to_marker
  fi
  cat_with_unread
}
cat_with_unread () {
  while [ $UNREAD_DEPTH != 0 ] ; do
    READ
    : "READ => $LINE"
    ECHO "$LINE"
  done
  cat
}
skip_to_marker () {
  while READ &&
  #: "READ => $LINE" &&
    case "$LINE" in
      "$CONTENT_BEGIN_MARKER") ! : ;;
      *) : ;;
    esac
  do : ; done
}
create_output () {
  create_file 755 "$OUTPUT_FILE" "$@"
}
with_input_from () {
  IN="$1" ; shift
  case "$IN" in
    ""|/dev/null) : from null ; "$@" < /dev/null ;;
    -) : from stdin ; "$@" ;;
    *) : from file "$IN" ; "$@" < "$IN" ;;
  esac
}
with_input () {
  with_input_from "${UPDATE:-$LISP_CONTENT}" "$@"
}
with_output () {
  case "${OUTPUT_FILE}" in
    "") ABORT "output file not specified" ;;
    /dev/null) : ;;
    -) "$@" ;;
    *) create_output "$@" ;;
  esac
}
make_output_file () {
  if [ -n "$DUMP" ] ; then
    dump_image_and_continue
  else
    do_make_output_file
  fi
}
do_make_output_file () {
  with_output with_input make_loader
}

execute_code () {
  run_code "$@"
}
do_run_code () {
  eval "$(print_shell_wrapper_body)"
  if [ -n "$LISP_CONTENT" ] ; then
    export CL_LAUNCH_FILE="$LISP_CONTENT"
  else
    unset CL_LAUNCH_FILE
  fi
  LAUNCH_FUN='funcall(intern(string :run):cl-launch)'
  LAUNCH_FORMS="$(load_form "$PROG";print_lisp_launch)"
  try_all_lisps "$@"
}
run_code () {
  ### Note: when dumping an image, run_code gets locally redefined
  ### by do_dump_image_and_continue, and restored by do_dump_image
  do_run_code "$@"
}
dump_image_and_continue () {
  case "$UPDATE" in
    -) SOFTWARE_CODE="$(cat)"
       ECHO "$SOFTWARE_CODE" | do_dump_image_and_continue "$@" ;;
    *) do_dump_image_and_continue "$@" ;;
  esac
}
do_dump_image_and_continue () {
  ORIG_WRAPPER_CODE="$WRAPPER_CODE"
  run_code () {
    WRAPPER_CODE="$WRAPPER_CODE
DO_LISP=do_dump_image"
    do_run_code "$@"
  }
  if [ "x$DUMP" = "x!" ] ; then
    if [ "x$OUTPUT_FILE" = "x!" ] ; then
      abort 14 "Image dump required but neither dump file nor output file specified"
    else
      DUMP="$OUTPUT_FILE"
    fi
  fi
  IMAGE=
  execute_code "$@"
}
do_dump_image () {
  : do_dump_image "$@"
  run_code () {
    do_run_code "$@"
  }
  if [ -n "$INCLUDE_PATH" ] ; then
    export CL_LAUNCH_HEADER="$INCLUDE_PATH/launcher.lisp"
  else
    export CL_LAUNCH_HEADER="$PROG"
  fi
  if [ "x$IMAGE_ARG" = "xNOT_SUPPORTED_YET" ] ; then
      abort 13 "Image dumping not supported with implementation $IMPL.
Try specifying a supported implementation with option --lisp (or \$LISP)"
  fi
  if [ -n "$STANDALONE_EXECUTABLE" ] ; then
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] ; then
      # disabled optimization: also for || [ "x$OUTPUT_FILE" = "x!" ]
      # as it doesn't play nice with older versions of SBCL, ECL, etc.,
      # that do not support standalone executables.
      export CL_LAUNCH_STANDALONE=t
    fi
  else
    if [ "x$DUMP" = "x$OUTPUT_FILE" ] ; then
      abort 15 "This implementation does not support dumping a standalone executable image"
    fi
  fi
  license_information
  # Use LOAD_IMAGE if it exists
  compute_image_path "$LOAD_IMAGE"
  ( do_exec_lisp ) || abort 22 "Failed to dump an image"
  case "$UPDATE" in
    -) ECHO "$SOFTWARE_CODE" | use_dumped_image "$@" ;;
    *) use_dumped_image "$@" ;;
  esac
}
use_dumped_image () {
  : use_dumped_image $OUTPUT_FILE -- standalone: ${CL_LAUNCH_STANDALONE}
  compute_image_path "$DUMP"
  case "${CL_LAUNCH_STANDALONE}:${OUTPUT_FILE}" in
    :!) invoke_image "$@" ;;
    :*) make_image_invoker ;;
    t:!) if [ -n "$CL_LAUNCH_VERBOSE" ] ; then set -x ; fi ;
        ${IMAGE} "$@" ;;
    t:*) : nothing to do ;;
  esac
}
make_image_invoker () {
  WRAPPER_CODE="$ORIG_WRAPPER_CODE"
  with_output with_input make_image_invocation_script
}
compute_image_path () {
  if [ -n "$1" ] ; then
    IMAGE_BASE="$(basename "$1")"
    IMAGE_DIR="${INCLUDE_PATH:-$(dirname "$1")}"
    IMAGE=${IMAGE_DIR}/${IMAGE_BASE}
  else
    IMAGE_BASE=
    IMAGE_DIR=
    IMAGE=
  fi
}

prepare_invocation_configuration () {
 LISP=$IMPL
 EXTRA_CONFIG_VARIABLES="LISP $OPTIONS_ARG"
 if eval "[ -n \"\$$BIN_ARG\" ]" ; then
   EXTRA_CONFIG_VARIABLES="$EXTRA_CONFIG_VARIABLES $BIN_ARG"
 fi
}
make_image_invocation_script () {
 prepare_invocation_configuration
 include_script_configuration_and_headers
 make_image_invocation
 include_lisp_content
}
make_image_invocation () {
 include_shell_wrapper
 if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
   echo "$BIN_ARG=$IMAGE"
 fi
 cat<<END
ensure_implementation $IMPL
invoke_image "\$@"
ABORT
# |#
END
}
do_it () {
  guess_defaults
  try_resource_files
  process_software_1 "$@"
  exit
}
process_software_1 () {
  # Stage 1: extract the configuration (if required)
  if [ -n "$UPDATE" ] ; then
    extract_and_process_software_2 "$@"
  else
    adjust_configuration
    process_software_2 "$@"
  fi
}
extract_and_process_software_2 () {
  with_input ensure_configuration
  if [ "x-" = "x$UPDATE" ] ; then
    extract_lisp_content | process_software_2 "$@"
  else
    process_software_2 "$@"
  fi
}
process_software_2 () {
  compute_image_path "$LOAD_IMAGE"
  # we have a configuration, now, ensure we have an image if needed
  if [ -n "$DUMP" ] ; then
    dump_image_and_continue "$@"
  else
    process_software_3 "$@"
  fi
}
process_software_3 () {
  # we have a configuration and no dump, now either execute or create script
  case "${OUTPUT_FILE}" in
    !) execute_code "$@" ;;
    *) make_output_file ;;
  esac
}
all () {
  process_options "$@"
  do_it
}

### Autoloading test infrastructure
for i in test test_clean tests do_test redo_test do_tests shell_tests all_tests clisp_tests ; do
  eval "$i () { . $(dirname $0)/cl-launch-tests.sh ; $i \"\${1+\$@}\" ;}"
done

### Installation
update () {
  wget -O cl-launch.sh "${CL_LAUNCH_URL}"
  chmod a+x cl-launch.sh
}
install () {
  if [ -z "$INCLUDE_PATH" ] || [ -z "$OUTPUT_FILE" ] ; then
    ABORT "example usage:
        $PROG -I /usr/share/common-lisp/source/cl-launch \\
              -l '$DEFAULT_LISPS' \\
              -o /usr/bin/cl-launch -B install"
  fi
  install_path
  install_bin
}
print_cl_launch_asd () {
  cat<<END
;;; -*- Lisp -*-
;; This file is for the sake of building systems that depend on cl-launch,
;; and/or binaries from implementations that link instead of dump (i.e. ECL).
;; cl-launch also used to be used as a way to redirect fasls, like
;; asdf-binary-locations or common-lisp-controller, in times before ASDF 2.
;;
;; It is only safe to upgrade ASDF itself as part of an ASDF operation
;; if the initial ASDF is more recent than 2.014.8.
;; If the initial ASDF isn't, you're likely in trouble.
;;
(asdf:defsystem :cl-launch
  :defsystem-depends-on ("asdf-package-system")
  :class :package-inferred-system
  :depends-on ((:version "asdf" "3.1.2")) ; we want some recent enough ASDF and UIOP
  :licence "MIT"
  :components ((:file "launcher")))
END
}
print_build_xcvb () {
  cat<<END
#+xcvb
(module
  (:fullname "cl-launch"
   :supersedes-asdf ("cl-launch")
   :build-depends-on ((:asdf "/uiop"))
   :depends-on ("launcher")))
END
}
generate_install_files () {
  DO create_file 755 "cl-launch" print_configured_launcher &&
  DO create_file 644 "wrapper.sh" print_shell_wrapper &&
  DO create_file 644 "launcher.lisp" print_lisp_launcher &&
  DO create_file 644 "cl-launch.asd" print_cl_launch_asd
  DO create_file 644 "build.xcvb" print_build_xcvb
}
install_path () {
  DO mkdir -p "$INCLUDE_PATH" &&
  DO create_file 644 "$INCLUDE_PATH/wrapper.sh" print_shell_wrapper &&
  DO create_file 644 "$INCLUDE_PATH/launcher.lisp" print_lisp_launcher &&
  DO create_file 644 "$INCLUDE_PATH/cl-launch.asd" print_cl_launch_asd
  DO create_file 644 "$INCLUDE_PATH/build.xcvb" print_build_xcvb
}
configure_launcher () {
  sed -e \
      's,^\(DEFAULT_LISPS\)=.*$,\1="'"${1}"'",
       s,^\(DEFAULT_INCLUDE_PATH\)=.*$,\1='"${2%/}"',
       s,^\(DEFAULT_USE_CL_LAUNCHRC\)=.*$,\1="'"${3}"'",
       s,^\(DEFAULT_USE_CLBUILD\)=.*$,\1="'"${4}"'",
       s,^\(DEFAULT_USE_QUICKLISP\)=.*$,\1="'"${5}"'",'
}
print_configured_launcher () {
  configure_launcher \
  "$LISPS" "$INCLUDE_PATH" "$USE_CL_LAUNCHRC" "$USE_CLBUILD" "$USE_QUICKLISP" < "$PROG"
}
install_bin () {
  DO create_file 755 "$OUTPUT_FILE" print_configured_launcher
}

### The meaty stuff: shell wrapper and Lisp loader
### That's where you want to add support for new Lisp implementations
print_shell_wrapper () {
  echo "# cl-launch ${CL_LAUNCH_VERSION} shell wrapper
#   Find and execute the most appropriate supported Lisp implementation
#   to evaluate software prepared with cl-launch.
#"
  include_license
  print_basic_functions
  print_shell_wrapper_body
}

# We must evaluate everything we need in only one form, because
# (1) SBCL (and other lisps?) refuses to execute several forms per --eval, and
# (2) clisp insists on printing every provided form, and we want to avoid that.
# We avoid this undesired output by ensuring that there is only one form,
# that quits before clisp prints anything, and that cause a SBCL error.
# Inside this form, we use #. to evaluate things before other things are read.
# Thus we may ensure that the CL-LAUNCH package exists before we attempt
# to read anything in it. Note that clisp *does* require the HASH_BANG_FORM,
# because we're not invoking our script using the clisp syntax.

print_shell_wrapper_body () {
  cat <<'EOF'
DO_LISP=do_exec_lisp
HASH_BANG_FORM='(set-dispatch-macro-character #\# #\! (lambda(stream char arg)(declare(ignore char arg))(values(read-line stream))))'
PACKAGE_FORM="#.(progn(defpackage :uiop/image (:use :cl))())#.(progn(declaim (special uiop/image::*command-line-arguments*))())"
MAYBE_PACKAGE_FORM=
PROGN="(progn"
NGORP=")"

#implementation_foo () {
#  implementation "${foo:-foo}" || return 1
#  OPTIONS=${FOO_OPTIONS:- --option-to-hush-the-banner --option-to-avoid-user-init-script}
#  EVAL=--option-to-pass-a-form-to-Lisp
#  ENDARGS="--option-to-end-Lisp-arguments-and-start-user-arguments"
#  IMAGE_ARG="--option-to-specify-an-image" # "EXECUTABLE_IMAGE" if instead of foo --core x.core you just ./x.core
#  EXEC_LISP=exec_lisp # or some other thing
#  BIN_ARG=FOO # name of the variable with which to override Lisp binary location
#  OPTIONS_ARG=FOO_OPTIONS # name of the variable used above
#  [ -z "$CL_LAUNCH_DEBUG" ] && OPTIONS="${OPTIONS} --option-to-disable-debugger"
#}
implementation_abcl () {
  implementation "${ABCL:-abcl}" || return 1
  OPTIONS="${ABCL_OPTIONS:- --noinform --noinit}" # --nosystem
  EVAL=--eval
  ENDARGS="--"
  IMAGE_ARG=NOT_SUPPORTED_YET
  EXEC_LISP=exec_lisp
  BIN_ARG=ABCL
  OPTIONS_ARG=ABCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --batch" # -backtrace-on-error ???
  fi
}
__implementation_allegro () {
  OPTIONS="${ALLEGRO_OPTIONS:- -QQ -qq}"
  EVAL=-e
  ENDARGS=--
  IMAGE_ARG=-I
  EXEC_LISP=exec_lisp
  BIN_ARG=ALLEGRO
  OPTIONS_ARG=ALLEGRO_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch -backtrace-on-error"
  fi
  HASH_BANG_FORM="(setf *readtable* (copy-readtable))${HASH_BANG_FORM}"
}
implementation_allegro () {
  implementation "${ALLEGRO:-alisp}" || return 1
  __implementation_allegro
}
implementation_allegromodern () {
  implementation "${ALLEGROMODERN:-mlisp}" || return 1
  __implementation_allegro
}

implementation_ccl () {
  # ClozureCL, nee OpenMCL, forked from MCL, formerly Macintosh Common Lisp, nee Coral Common Lisp
  implementation "${CCL:-ccl}" || return 1
  OPTIONS="${CCL_OPTIONS:- --no-init --quiet}"
  EVAL=--eval # -e
  # IMAGE_ARG=--image-name # -I
  IMAGE_ARG=EXECUTABLE_IMAGE # depends on our using :prepend-kernel t
  ENDARGS=--
  # (finish-output) is essential for ccl, that won't do it by default,
  # unlike the other lisp implementations tested.
  EXEC_LISP=exec_lisp
  # exec_lisp will work great for 1.1 and later.
  # For earlier versions, use exec_lisp_arg instead:
  # 1.0 doesn't support --, and the latest 1.1-pre060826 snapshot has a bug
  # whereby it doesn't stop at -- when looking for a -I or --image-file argument.
  STANDALONE_EXECUTABLE=t
  BIN_ARG=CCL
  OPTIONS_ARG=CCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --batch"
  fi
}
implementation_clisp () {
  implementation "${CLISP:-clisp}" || return 1
  OPTIONS="${CLISP_OPTIONS:- -norc --quiet --quiet}"
  EVAL=-x
  LOAD=-i
  ENDARGS="--"
  # if the first argument begins with - there might be problems,
  # so we avoid that and take the cdr or ext:*args*
  # IMAGE_ARG=-M # for use without :executable t
  IMAGE_ARG="EXECUTABLE_IMAGE" # we don't use this by default
  STANDALONE_EXECUTABLE=t # will mostly work as of clisp 2.48, but with a (in)security backdoor.
  # For details, see the thread at http://sourceforge.net/forum/message.php?msg_id=5532730
  EXEC_LISP=exec_lisp
  BIN_ARG=CLISP
  OPTIONS_ARG=CLISP_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -on-error exit"
  else
    OPTIONS="${OPTIONS} -on-error debug"
  fi
}
implementation_cmucl () {
  implementation "${CMUCL:-cmucl}" || return 1
  OPTIONS="${CMUCL_OPTIONS:- -quiet -noinit}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG=-core
  IMAGE_ARG="EXECUTABLE_IMAGE"
  STANDALONE_EXECUTABLE=t
  EXEC_LISP=exec_lisp # depends on a recent CMUCL. Works with 20B.
  BIN_ARG=CMUCL
  OPTIONS_ARG=CMUCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_ecl () {
  implementation "${ECL:-ecl}" || return 1
  OPTIONS="${ECL_OPTIONS:- -q -norc}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)"
    NGORP="))"
  fi
}
implementation_ecl_bytecodes () {
  implementation_ecl
  OPTIONS="${ECL_OPTIONS:- -q -norc}"
  OPTIONS="${OPTIONS} -eval (ext::install-bytecodes-compiler)"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)"
    NGORP="))"
  fi
}
implementation_mkcl () { ### Untested
  implementation "${MKCL:-mkcl}" || return 1
  OPTIONS="${MKCL_OPTIONS:- -q -norc}"
  EVAL=-eval
  ENDARGS=--
  #IMAGE_ARG="-q -load" # for :fasl
  IMAGE_ARG="EXECUTABLE_IMAGE" # for :program
  STANDALONE_EXECUTABLE=t
  BIN_ARG=ECL
  OPTIONS_ARG=ECL_OPTIONS
  EXEC_LISP=exec_lisp
  if [ -n "$CL_LAUNCH_DEBUG" ] ; then
    PROGN="(handler-bind((error'invoke-debugger))(progn(set'si::*break-enable*'t)" ## Check this one!
    NGORP="))"
  fi
}
implementation_gcl () {
  implementation "${GCL:-gcl}" || return 1
  OPTIONS="${GCL_OPTIONS}"
  EVAL=-eval
  ENDARGS=-- # -f ?n
  IMAGE_ARG=EXECUTABLE_IMAGE
  BIN_ARG=GCL
  OPTIONS_ARG=GCL_OPTIONS
  export GCL_ANSI=t
  EXEC_LISP=exec_lisp
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_lispworks () { ### NOT EXTENSIVELY TESTED
  # http://www.lispworks.com/documentation/lw60/LW/html/lw-484.htm#pgfId-891723
  USE_CLBUILD= implementation "${LISPWORKS:-lispworks-console}" || return 1
  OPTIONS="${LISPWORKS_OPTIONS:- -siteinit - -init -}" #
  LOAD=-build #### way to avoid splash screen (?) and dump executable
  # LOAD=-load
  EVAL=-eval # Exists in LW 6.0,
  #! ENDARGS="--"
  IMAGE_ARG="EXECUTABLE_IMAGE" # we don't use this by default
  EXEC_LISP=exec_lisp_file # for use with -build
  STANDALONE_EXECUTABLE=t
  BIN_ARG=LISPWORKS
  OPTIONS_ARG=LISPWORKS_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    : # OPTIONS="${OPTIONS} ..."
  else
    : # OPTIONS="${OPTIONS} ..."
  fi
  export LWLICENSE=$(dirname $LISP_BIN)/lwlicense
}
implementation_sbcl () {
  implementation "${SBCL:-sbcl}" || return 1
  OPTIONS="${SBCL_OPTIONS:- --noinform --userinit /dev/null}"
  # We purposefully specify --userinit /dev/null but NOT --sysinit /dev/null
  EVAL=--eval # SBCL's eval can only handle one form per argument.
  ENDARGS=--end-toplevel-options
  IMAGE_ARG="EXECUTABLE_IMAGE" # we use executable images
  # if you want to test non-executable images, uncomment the one below,
  # and comment out the :executable t in (defun dump-image ...)
  # -IMAGE_ARG=--core
  STANDALONE_EXECUTABLE=t # requires sbcl 1.0.21.24 or later.
  EXEC_LISP=exec_lisp
  BIN_ARG=SBCL
  OPTIONS_ARG=SBCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} --disable-debugger"
  fi
}
implementation_scl () {
  implementation ${SCL:=scl} || return 1
  OPTIONS="${SCL_OPTIONS:- -quiet -noinit}"
  EVAL=-eval
  ENDARGS=--
  IMAGE_ARG=-core
  EXEC_LISP=exec_lisp
  BIN_ARG=SCL
  OPTIONS_ARG=SCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    OPTIONS="${OPTIONS} -batch"
  fi
}
implementation_xcl () {
  implementation "${XCL:-xcl}" || return 1
  OPTIONS="${XCL_OPTIONS:- --noinform --no-userinit}" # --no-siteinit
  EVAL=--eval
  ENDARGS="--"
  IMAGE_ARG=NOT_SUPPORTED_YET
  EXEC_LISP=exec_lisp
  BIN_ARG=XCL
  OPTIONS_ARG=XCL_OPTIONS
  if [ -z "$CL_LAUNCH_DEBUG" ] ; then
    : # Not supported yet
  fi
}
prepare_arg_form () {
  ENDARGS= F=
  for arg ; do
    F="$F\"$(kwote "$arg")\""
  done
  MAYBE_PACKAGE_FORM=" $PACKAGE_FORM"
  LAUNCH_FORMS="(setf uiop/image::*command-line-arguments*'($F))${LAUNCH_FORMS}"
}
# Aliases
implementation_alisp () {
  implementation_allegro "$@"
}
implementation_mlisp () {
  implementation_allegromodern "$@"
}
implementation_gclcvs () {
  implementation "${GCLCVS:=gclcvs}" || return 1
  GCL="$GCLCVS"
  implementation_gcl "$@" && BIN_ARG=GCLCVS
}
implementation_lisp () {
  implementation ${CMULISP:=lisp} || return 1
  CMUCL=$CMULISP
  implementation_cmucl "$@"
}
implementation_openmcl () {
  implementation "${OPENMCL:=openmcl}" || return 1
  CCL="$OPENMCL"
  CCL_OPTIONS="$OPENMCL_OPTIONS"
  implementation_ccl "$@" && BIN_ARG=OPENMCL
}

exec_lisp_noarg () {
  prepare_arg_form "$@"
  exec_lisp
}
exec_lisp_file () {
  prepare_arg_form "$@"
  LOADFILE=${TMPDIR:-/tmp}/cl-load-file-$(date +%s)-$$
  cat > $LOADFILE <<END
${MAYBE_PACKAGE_FORM}
${HASH_BANG_FORM}
${LAUNCH_FORMS}
END
  $LISP_BIN $IMAGE_OPT $IMAGE $OPTIONS $LOAD "$LOADFILE"
  RET=$?
  rm -f $LOADFILE
  exit $RET
}
implementation_clisp_noarg () {
  implementation_clisp
  EXEC_LISP=exec_lisp_noarg
  # For testing purposes
}
implementation_clisp_file () {
  implementation_clisp
  EXEC_LISP=exec_lisp_file
  # For testing purposes
}
implementation () {
  if [ -n "$USE_CLBUILD" ] ; then
    if CLBUILD_BIN="`which clbuild 2> /dev/null`" ; then
      LISP_BIN="$CLBUILD_BIN --implementation $IMPL lisp"
      return 0
    else
      return 1
    fi
  elif [ -x "$1" ] ; then
    LISP_BIN="$1"
    return 0
  elif LISP_BIN="`which "$1" 2> /dev/null`" ; then
    return 0
  else
    return 1
  fi
}
trylisp () {
  IMPL="$1" ; shift
  implementation_${IMPL} "$@"
}
do_exec_lisp () {
  if [ -n "$IMAGE" ] ; then
    if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
      LISP_BIN= IMAGE_OPT=
    else
      IMAGE_OPT="$IMAGE_ARG"
    fi
  fi
  $EXEC_LISP "$@"
}
no_implementation_found () {
  ABORT "$PROG: Cannot find a supported lisp implementation.
Tried the following: $*"
}
ensure_implementation () {
  trylisp "$1" || no_implementation_found "$1"
}
try_all_lisps () {
  for l in $LISP $LISPS ; do
    if trylisp $l ; then
      $DO_LISP "$@"
      return 0
    fi
  done
  no_implementation_found "$LISP $LISPS"
}
exec_lisp () {
  # SBCL wants only one form per --eval so we need put everything in one progn.
  # However we also want any in-package form to be evaluated before any of the
  # remaining forms is read, so we get it to be evaluated at read-time as the
  # first thing in the main progn.
  # GNU clisp allows multiple forms per -x but prints the result of every form
  # evaluated and so we also need put everything in a single progn, and that progn
  # must quit before it may return to the clisp frame that would print its value.
  # CMUCL allows multiple forms per -eval and won't print values, so is ok anyway.
  # I don't know about other Lisps, but they will all work this way.
  LAUNCH_FORM="${PROGN}${MAYBE_PACKAGE_FORM}${HASH_BANG_FORM}${LAUNCH_FORMS}${NGORP}"
  ### This is partial support for CLBUILD.
  if [ -n "$USE_CLBUILD" ] ; then
    if [ -z "$IMAGE_OPT" ] ; then
      OPTIONS=
    else
      ABORT "Cannot use clbuild with a non-executable image different from clbuild's"
    fi
  fi
  if [ -n "$CL_LAUNCH_VERBOSE" ] ; then set -x ; fi
  exec $LISP_BIN $IMAGE_OPT $IMAGE $OPTIONS $EVAL "$LAUNCH_FORM" $ENDARGS "$@"
}
launch_self () {
  LAUNCH_FORMS="$(load_form "$PROG")"
  try_all_lisps "$@"
}
invoke_image () {
  if [ "x$IMAGE_ARG" = xEXECUTABLE_IMAGE ] ; then
    LISP_BIN= IMAGE_OPT=
  else
    IMAGE_OPT="$IMAGE_ARG"
  fi
  PACKAGE_FORM=
  HASH_BANG_FORM=
  LAUNCH_FORMS="(uiop:restore-image)"
  "$EXEC_LISP" "$@"
}

export CL_LAUNCH_PID=$$
export CL_LAUNCH_FILE="$PROG"

## execute configuration-provided code
eval "$WRAPPER_CODE"

### END OF CL-LAUNCH SHELL WRAPPER
EOF
}
: ' Useful tidbit for dichotomy-debugging Lisp code:
(defvar *x* 0) (defun xx () (format t "*x* ~D~%" (incf *x*) (finish-output))) (xx)
(xx)
'
cl_fragment () {
  if [ -n "$CL_HEADER" ] ; then
    ECHO "#-cl-launch"
  fi
  cat
}
do_print_lisp_implementation () {
  ECHO "$IMPL"
}
print_lisp_implementation () {
  eval "$(print_shell_wrapper_body)"
  DO_LISP=do_print_lisp_implementation
  try_all_lisps
}
do_print_lisp_binary_path () {
  ECHO "$LISP_BIN"
}
print_lisp_binary_path () {
  eval "$(print_shell_wrapper_body)"
  DO_LISP=do_print_lisp_binary_path
  try_all_lisps
}
print_lisp_header () {
  CL_HEADER=t
  print_lisp_code
  echo ";;;;; Return to the default package."
  echo "(cl:in-package :cl-user)"
  print_lisp_code_bottom
}
print_lisp_launcher () {
  CL_HEADER=
  print_lisp_code
  echo ; echo "(cl-launch::compute-arguments)"
  print_lisp_code_bottom
}
print_lisp_setup () {
  OPTION -q
  print_lisp_launcher
  OPTION -x -s asdf -i "(let ((*package* (find-package :cl-launch))) (format t \"(cl-launch::initialize-asdf ~S)~%\" \"$(kwote $SOURCE_REGISTRY)\"))" --
}

print_lisp_code () {
  echo "#+xcvb (module (:build-depends-on () :depends-on (\"/asdf\")))"
  echo "#| ;;; cl-launch ${CL_LAUNCH_VERSION} lisp header"
  include_license
# HACK: this whole file is itself readable as Lisp code, and its meaning
# is then that of the cl-launch lisp header code enclosed herein.
# |# Last bit of Karma
cat<<'NIL'

|# ;;;; Silence our lisp implementation for quiet batch use...

#| We'd like to evaluate as little as possible of the code without compilation.
 This poses a typical bootstrapping problem: the more sophistication we want
 to distinguish what to put where in what dynamic environment, the more code
 we have to evaluate before we may actually load compiled files. And, then,
 it is a waste of time to try to compile said code into a file. Moving things
 to the shell can only help so much, and reduces flexibility. Our best bet is
 to tell sbcl or cmucl to not try to optimize too hard.
|#
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
(eval-when (:compile-toplevel :load-toplevel :execute)
  ;; Configure the printer
  (setf *print-readably* nil ; allegro 5.0 may bork without this
        *print-level* nil)
  ;; Hush the compiler and loader.
  (setf *load-verbose* nil *compile-verbose* nil *compile-print* nil *load-print* nil)
  ;; The code below exemplifies how to try super-hard to load ASDF 3 from standard locations,
  ;; by trying nice methods first, then increasingly desperate ones.
  ;; Stage 1 is to load ASDF at all.
  ;; Stage 2 is to upgrade to whichever ASDF installation the user has configured (if any).
  ;; Versions older than ASDF 3.1 need to be told about ~/common-lisp/
  ;; ASDF 1 has no output translation layer, so can be configured to load ASDF 3
  ;; only if ASDF 3 is in a predictable place under the user's homedir, thus
  ;; ~/common-lisp/asdf/ or ~/.local/share/common-lisp/source/asdf/ only.
  (block nil
    (let ((required-asdf-version  "3.1.2")
          (verbose *load-verbose*))
      (labels ((asdf-symbol (name)
                 (and (find-package :asdf) (find-symbol (string name) :asdf)))
               (asdf-call (name &rest args)
                 (apply (asdf-symbol name) args))
               (asdf-version ()
                 (when (find-package :asdf)
                   (or (symbol-value (or (asdf-symbol '*asdf-version*)
                                         (asdf-symbol '*asdf-revision*)))
                       "1.0")))
               (maybe-display (message)
                 (when (and verbose message) (format t "~&~A~%" message)))
               (call-maybe-verbosely (message function &rest args)
                 (cond
                   (verbose
                    (maybe-display message)
                    (apply function args))
                   (t
                    #+abcl ;; Bug in ABCL 1.3.0: without this, loading asdf.fasl shows warnings
                    (let* ((uc (asdf-symbol '*uninteresting-conditions*))
                           (vars (when uc (list uc)))
                           (vals (when uc (list (cons 'warning (symbol-value uc))))))
                      (progv vars vals
                        (handler-bind ((warning #'muffle-warning))
                          (apply function args))))
                    #-abcl
                    (handler-bind ((warning #'muffle-warning))
                      (apply function args)))))
               (try-stage-1 (message function)
                 (ignore-errors
                  (call-maybe-verbosely (format nil "Trying to ~A" message) function))
                 (maybe-done-stage-1))
               (subpath (parent &key directory name type)
                 (merge-pathnames (make-pathname :defaults parent :name name :type type :version nil
                                                 :directory (cons :relative directory))
                                  parent))
               (build/asdf.lisp (x) (subpath x :directory '("build") :name "asdf" :type "lisp"))
               (visible-default-user-asdf-directory ()
                 (subpath (user-homedir-pathname) :directory '("common-lisp" "asdf")))
               (visible-default-user-asdf-lisp ()
                 (build/asdf.lisp (visible-default-user-asdf-directory)))
               (hidden-default-user-asdf-directory ()
                 (subpath (user-homedir-pathname) :directory '(".local" "share" "common-lisp" "asdf")))
               (hidden-default-user-asdf-lisp ()
                 (build/asdf.lisp (hidden-default-user-asdf-directory)))
               (try-file-stage-1 (name explanation base root sub)
                 (try-stage-1
                  (format nil "load ASDF from ~A/ under the ~A CL source directory ~A~{~A/~}"
                          name explanation root sub)
                  #'(lambda () (load (build/asdf.lisp
                                      (subpath base :directory (append sub (list name))))))))
               (stage-1 () ;; Try to load ASDF at all, any ASDF.
                 (try-stage-1
                  ;; Do nothing if ASDF is already loaded
                  "use an already loaded ASDF"
                  (constantly nil))
                 (try-stage-1
                  "require ASDF from the implementation"
                  ;; Most implementations provide ASDF, but while most of them are case-insensitive,
                  ;; CLISP is case-sensitive, so we need to specify a lowercase string,
                  ;; and not the keyword :asdf or symbol 'asdf.
                  ;; Most recent implementations provide ASDF 3, but some of them only ASDF 2
                  ;; and antique versions only of ASDF 1.
                  #'(lambda () (funcall 'require "asdf")))
                 (try-file-stage-1 "asdf" "default (visible)" (user-homedir-pathname)
                                   "~/" '("common-lisp"))
                 (try-file-stage-1 "asdf" "default (hidden)" (user-homedir-pathname)
                                   "~/" '(".local" "share" "common-lisp"))
                 #+(or unix linux bsd darwin)
                 (progn
                   (loop :for (name path) :in '(("local system" ("local")) ("managed system" ()))
                         :do (loop :for sub :in '(() ("source"))
                                   :do (try-file-stage-1
                                        "asdf" name #p"/" "/"
                                        (append '("usr") path '("share" "common-lisp") sub))))
                   (try-file-stage-1 "cl-asdf" "managed system" #p"/" "/"
                                     '("usr" "share" "common-lisp" "source")))
                 (error "Could not load ASDF."))
               (maybe-done-stage-1 ()
                 ;; If we have ASDF, then go to stage 2: have it upgrade itself.
                 (when (member :asdf *features*)
                   (maybe-display (format nil "Found ASDF ~A" (asdf-version)))
                   (stage-2))) ;; doesn't return.
               (centrally-register (path)
                 (let ((r (asdf-symbol '*central-registry*)))
                   (pushnew path (symbol-value r))
                   (pushnew (subpath path :directory '("uiop")) (symbol-value r))))
               (configure-asdf ()
                 ;; configure older versions of ASDF, as needed
                 (cond
                   ((probe-file (visible-default-user-asdf-lisp))
                    (unless (member :asdf3.1 *features*)
                      (maybe-display "Telling this old ASDF about your ~/common-lisp/asdf/")
                      (centrally-register (visible-default-user-asdf-directory))))
                   ((probe-file (hidden-default-user-asdf-lisp))
                    (unless (member :asdf2 *features*)
                      (maybe-display "Telling this antique ASDF about your ~/.local/share/common-lisp/asdf/")
                      (centrally-register (hidden-default-user-asdf-directory))))))
               (maybe-done-stage-2 ()
                 (when (ignore-errors (asdf-call 'version-satisfies
                                                 (asdf-version) required-asdf-version))
                   (when verbose
                     (format t "~&Victory! We now have ASDF ~A~%" (asdf-version)))
                   (return)))
               (stage-2 ()
                 ;; We have ASDF, now have it upgrade itself.
                 (configure-asdf)
                 (when (asdf-call 'find-system :asdf nil)
                   (call-maybe-verbosely
                    "Trying to upgrade ASDF"
                    (asdf-symbol 'operate) (asdf-symbol 'load-op) :asdf) :verbose nil)
                 (maybe-done-stage-2)
                 (error "We could only load ASDF ~A but we need ASDF ~A"
                        (asdf-version) required-asdf-version)))
        ;; :asdf3.1 is both more recent than required and self-upgrading, so doesn't need this dance
        ;; :asdf3 is self-upgrading but might not be recent enough (it could be a pre-release).
        (unless (member :asdf3.1 *features*)
          (call-maybe-verbosely nil #'stage-1)))))

  (in-package :asdf))
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
;; Because of ASDF upgrade punting, this ASDF package may be a new one.
(eval-when (:compile-toplevel :load-toplevel :execute)
  (unless (or #+asdf2 (asdf:version-satisfies (asdf:asdf-version) "3.1.2"))
    (error "cl-launch requires ASDF 3.1.2 or later")))
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
;;;; Create cl-launch with UIOP.
(progn
(uiop:define-package :cl-launch
  (:use :common-lisp :uiop :asdf)
  (:export #:compile-and-load-file))

(in-package :cl-launch))
NIL
":" 't #-cl-launch ;'; cl_fragment<<'NIL'
;;;; cl-launch initialization code
(progn
(defvar *cl-launch-header* nil) ;; name of the file with this Lisp header (if any)
(defvar *cl-launch-file* nil) ;; name of the file with the user code (if any)
(defvar *verbose* nil)
(defun dump-stream-to-file (i n)
  (with-output-file (o n :if-exists :rename-and-delete) (copy-stream-to-stream i o)))
(defun dump-sexp-to-file (x n)
  (with-output-file (o n :if-exists :rename-and-delete) (write x :stream o :pretty t :readably t)))
(defvar *temporary-filenames* nil)
(defvar *temporary-file-prefix*
  (native-namestring (subpathname *temporary-directory*
                                  (strcat "cl-launch-" (getenvp "CL_LAUNCH_PID")))))
(defun make-temporary-filename (x)
  (parse-native-namestring (strcat *temporary-file-prefix* x)))
(defun register-temporary-filename (n)
  (push n *temporary-filenames*)
  n)
(defun temporary-filename (x)
  (register-temporary-filename (make-temporary-filename x)))
(defun temporary-file-from-foo (dumper arg x)
  (let ((n (temporary-filename x)))
    (funcall dumper arg n)
    n))
(defun temporary-file-from-stream (i x)
  (temporary-file-from-foo #'dump-stream-to-file i x))
(defun temporary-file-from-string (i x)
  (temporary-file-from-foo
   #'(lambda (i n) (with-output-file (o n :if-exists :rename-and-delete) (princ i o))) i x))
(defun temporary-file-from-sexp (i x)
  (temporary-file-from-foo #'dump-sexp-to-file i x))
(defun temporary-file-from-code (i x)
  (if (stringp i)
      (temporary-file-from-string i x)
      (temporary-file-from-sexp i x)))
(defun temporary-file-from-file (f x)
  (with-open-file (i f :direction :input :if-does-not-exist :error)
    (temporary-file-from-stream i x)))
(defun ensure-lisp-file-name (x &optional (name "load.lisp"))
  (if (equal (pathname-type x) "lisp") x (temporary-file-from-file x name)))
(defun ensure-lisp-loadable (x)
  (cond
    ((eq x t) (ensure-lisp-loadable (or *cl-launch-file* (error "Missing CL_LAUNCH_FILE"))))
    ((equal x "-") *standard-input*)
    ((or (streamp x) (pathnamep x)) x)
    ((stringp x) (ensure-absolute-pathname (parse-native-namestring x) #'getcwd))))
(defun ensure-lisp-file (x &optional (name "load.lisp"))
  (let ((x (ensure-lisp-loadable x)))
    (etypecase x
      (stream (temporary-file-from-stream x name))
      (pathname (ensure-lisp-file-name x name)))))
(defun cleanup-temporary-files ()
  (loop :for n = (pop *temporary-filenames*)
        :while n :do
          (delete-file-if-exists n)))
(defun file-newer-p (new-file old-file)
  "Returns true if NEW-FILE is strictly newer than OLD-FILE."
  (> (file-write-date new-file) (file-write-date old-file)))
(defun compile-and-load-file (source &key force-recompile
                              (verbose *verbose*) (load t)
                              output-file)
  "compiles and load specified SOURCE file, if either required by keyword
argument FORCE-RECOMPILE, or not yet existing, or not up-to-date.
Keyword argument VERBOSE specifies whether to be verbose.
Returns two values: the fasl path, and T if the file was (re)compiled"

  ;; When in doubt, don't trust - recompile. Indeed, there are
  ;; edge cases cases when on the first time of compiling a simple
  ;; auto-generated file (e.g. from the automated test suite), the
  ;; fasl ends up being written to disk within the same second as the
  ;; source was produced, which cannot be distinguished from the
  ;; reverse case where the source code was produced in the same split
  ;; second as the previous version was done compiling. Could be
  ;; tricky if a big system needs be recompiled as a dependency on an
  ;; automatically generated file, but for cl-launch those
  ;; dependencies are not detected anyway (BAD). If/when they are, and
  ;; lacking better timestamps than the filesystem provides, you
  ;; should sleep after you generate your source code.
  (let* (#+gcl
         (maybe-delete
           (unless (equal (pathname-type source) "lisp")
             (let ((temp (make-temporary-filename (strcat (pathname-name source) ".lisp"))))
               (copy-file source temp)
               (setf source temp))))
         (truesource (truename source))
         (fasl (or output-file (compile-file-pathname* truesource)))
         (compiled-p
          (when (or force-recompile
                    (not (probe-file fasl))
                    (not (file-newer-p fasl source)))
            (ensure-directories-exist fasl)
            (multiple-value-bind (path warnings failures)
                (compile-file* truesource :output-file fasl)
              (declare (ignorable warnings failures))
              (unless (equal (truename fasl) (truename path))
                (error "cl-launch: file compiled to ~A, expected ~A" path fasl))
              (when failures
                (error "cl-launch: failures while compiling ~A" source)))
            t)))
    (when load
      (load* fasl :verbose verbose))
    #+gcl (delete-file-if-exists maybe-delete)
    (values fasl compiled-p)))
(defun load-file (source &key output-file)
  (declare (ignorable output-file))
  #-(or gcl (and ecl (not dlopen)))
  (compile-and-load-file source :verbose *verbose* :output-file output-file)
  #+gcl
  (let* ((pn (parse-namestring source))) ; when compiling, gcl 2.6 will always
    (if (pathname-type pn) ; add a type .lsp if type is missing, to avoid compilation
      (compile-and-load-file source :verbose *verbose* :output-file output-file)
      (load source :verbose *verbose*)))
  #+(and ecl (not dlopen))
  (load source :verbose *verbose*))
(defun compute-arguments ()
  (setf *cl-launch-file* (getenvp "CL_LAUNCH_FILE")
        *cl-launch-header* (getenvp "CL_LAUNCH_HEADER")
        *verbose* (when (getenvp "CL_LAUNCH_VERBOSE") t)))

(asdf::register-preloaded-system "cl-launch")

(defun load-sys (system)
  (if (find-package :quicklisp)
      (let ((*standard-output* (make-broadcast-stream)))
        (symbol-call :quicklisp :quickload system))
      (asdf:load-system system)))

;;; We need this on all implementations when dumping an image,
;;; so that --eval and --file statements may properly depend
;;; on previously loaded systems, etc.
;;; To do it right, though, we want to only create a file
;;; for the --eval statement if needed by ECL...
(defvar *dependency-counter* 0)
(defun cl-launch-files ()
  (when (pathnamep *cl-launch-file*)
    (list *cl-launch-file*)))
(defun make-temporary-system (stem rdeps options)
  ;; Make a temporary system with given name stem and options
  ;; return the new list of dependencies, i.e. a singleton of the actual system name.
  (let ((sys (strcat "cl-launch-" stem)))
    (eval `(handler-bind ((warning #'muffle-warning))
             (defsystem ,sys :pathname ,*temporary-directory* :depends-on ,(reverse rdeps) ,@options)
             (defmethod input-files ((o operation) (s (eql (find-system ,sys))))
               ',(cl-launch-files))))
    (list sys)))
(defclass asdf::cl-source-file-in-package (cl-source-file)
  ((package :initarg :package :reader component-package)))
(defclass asdf::cl-source-code (source-file)
  ((code :initarg :code :initform nil :reader component-code)
   (package :initarg :package :reader component-package)))
(handler-bind ((warning #'muffle-warning))
  (defmethod perform :around ((o compile-op) (c asdf::cl-source-file-in-package))
    (let ((*package* (find-package (component-package c))))
      (call-next-method)))
  (defmethod component-pathname ((c asdf::cl-source-code)) nil)
  (defmethod perform ((o compile-op) (c asdf::cl-source-code)))
  (defmethod perform ((o load-op) (c asdf::cl-source-code))
    (let ((*package* (find-package (component-package c))))
      (eval-thunk (or (component-code c) (component-name c))))))
(defun make-dependency-system (rdeps options)
  ;; Make a system for given dependencies,
  ;; return the new list of dependencies, i.e. a singleton of the system name.
  (let ((name (format nil "build-~D" *dependency-counter*)))
    (incf *dependency-counter*)
    (make-temporary-system name rdeps options)))
(defun make-dependency (dump fun arg pkg previous)
  ;; Make a dependency, return the new list of dependencies
  (ecase fun
    ((:load)
       (let ((x (ensure-lisp-loadable arg)))
         (if (or (pathnamep x) #+(or ecl mkcl) dump)
           (let ((load-file (ensure-lisp-file x (format nil "load-~D.lisp" *dependency-counter*))))
             (make-dependency-system previous
              `(:components ((:cl-source-file-in-package ,(pathname-name load-file)
                              :package ,pkg :pathname ,(truename load-file))))))
           (make-dependency dump :eval `(load* ,x) pkg previous))))
    ((:eval)
     (if (and #+(or ecl mkcl) (not dump))
       (make-dependency-system previous
        `(:components ((:cl-source-code ,(format nil "eval-~D" *dependency-counter*)
                        :code ,arg :package :cl-user))))
       #+(or ecl mkcl)
       (with-input (i (temporary-file-from-code arg (format nil "eval-~D.lisp" *dependency-counter*)))
         (make-dependency dump :load i :cl-user previous))))
    ((:require)
     (cons `(:require ,arg) previous))
    ((:load-system)
     (cons arg previous))))

(defun build-program (dump build restart final init quit)
  (unwind-protect
       (let* ((*compile-verbose* *verbose*)
              #+ecl (c::*suppress-compiler-warnings* (not *verbose*))
              #+ecl (c::*suppress-compiler-notes* (not *verbose*))
              (standalone (and (getenvp "CL_LAUNCH_STANDALONE") t))
              (op (if standalone 'program-op 'image-op))
              (dependencies
                (loop :with r = ()
                      :for (fun arg pkg) :in
                      `((:load-system "asdf")
                        ,@(when dump ;; do we still want to include cl-launch in the dumped code,
                            #+(or ecl mkcl) ;; now that all the relevant runtime support is in UIOP?
                            (let ((header *cl-launch-header*)) ;; maybe for dependency timestamp?
                              (setf *features* (remove :cl-launch *features*))
                              `((:load ,(ensure-lisp-file header "header.lisp") :cl-user))))
                        ,@build
                        ,(let ((footer
                                 `(setf
                                   *package* (find-package :cl-user)
                                   *image-dumped-p* ,(when dump (if standalone :executable t))
                                   *image-entry-point*
                                   ,(when restart `(ensure-function ,(car restart) :package ,(cdr restart)))
                                   *image-prelude* ,init
                                   *image-postlude* ,final
                                   *lisp-interaction* ,(not quit))))
                           `(:eval ,footer :cl-user)))
                      :do (setf r (make-dependency dump fun arg pkg r))
                      :finally (return r)))
              (program-sys
                (make-temporary-system
                 "program" dependencies
                 `(:serial t
                   :build-operation ,op
                   :build-pathname ,(when dump (ensure-absolute-pathname dump #'getcwd))
                   :entry-point ,(when restart
                                   `(lambda ()
                                      (funcall (ensure-function ,(car restart) :package ,(cdr restart)))))
                   ;; Provide a sensible timestamp
                   ;; For SBCL and other platforms that die on dump-image, clean before the end:
                   ,@(if (version<= "3.1.1" (asdf-version))
                         `(:perform (image-op :before (o c)
                             (setf *features* (remove :cl-launched *features*))
                             (cleanup-temporary-files)))
                         (when dump
                           (error "Dumping an image with cl-launch 4 requires ASDF 3.1.1 or later")))))))
         (load-sys program-sys) ;; Give quicklisp a chance to download things
         (when dump
           (operate op program-sys)))
    (cleanup-temporary-files))
  (unless dump
    (restore-image))
  (quit 0))

(defun load-quicklisp ()
  (block nil
    (flet ((try (x) (when (probe-file* x) (return (load* x)))))
      (try (subpathname (user-homedir-pathname) "quicklisp/setup.lisp"))
      (try (subpathname (user-homedir-pathname) ".quicklisp/setup.lisp"))
      (error "Couldn't find quicklisp in your home directory. ~
              Go get it at http://www.quicklisp.org/beta/index.html"))))

(defun run (&key quicklisp source-registry build dump restart final init (quit t))
  (setf *lisp-interaction* (not quit))
  (with-fatal-condition-handler ()
    (pushnew :cl-launched *features*)
    (compute-arguments)
    (when source-registry (initialize-source-registry source-registry))
    (when quicklisp (load-quicklisp))
    (build-program dump build restart final init quit)))

(pushnew :cl-launch *features*))
NIL
#|
}
print_lisp_code_bottom () {
# |#
":" ; cat<<'NIL'

;;; END OF CL-LAUNCH LISP HEADER
NIL
#|
}

### There we are. Now do the job
[ $# -gt 0 ] || mini_help_abort
all "$@" ; exit

# |# ; What follows is Lisp code available when loading this file
