#!perl

use 5.010;
use strict;
use warnings;
use Log::ger; BEGIN { $ENV{LOG_LEVEL} //= 'info' }

use Perinci::CmdLine::Any;
use Perinci::CmdLineX::CommonOptions::SelfUpgrade;

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2023-11-20'; # DATE
our $DIST = 'App-instopt'; # DIST
our $VERSION = '0.021'; # VERSION

my $prefix = "/App/instopt/";

$Perinci::CmdLineX::CommonOptions::SelfUpgrade::_list_modules = sub {
    require Module::List::Tiny;
    my @modules = ('App::instopt');
    my $mods = PERLANCAR::Module::List::list_modules(
        'Software::Catalog::SW::', {list_modules=>1, recurse=>1});
    push @modules, $_ for sort keys %$mods;
    #log_debug "Modules to upgrade: %s", \@modules;
    @modules;
};

my $cli = Perinci::CmdLine::Any->new(
    url => $prefix,
    log => 1,
    subcommands => {
        'cleanup-download-dir'     => {url=>"${prefix}cleanup_download_dir"},
        'cleanup-install-dir'      => {url=>"${prefix}cleanup_install_dir"},
        'compare-versions'         => {url=>"${prefix}compare_versions"},
        'download-all'             => {url=>"${prefix}download_all"},
        'download'                 => {url=>"${prefix}download"},
        'is-downloaded-any'        => {url=>"${prefix}is_downloaded_any"},
        'is-downloaded-latest'     => {url=>"${prefix}is_downloaded_latest"},
        'is-installed-any'         => {url=>"${prefix}is_installed_any"},
        'is-installed-latest'      => {url=>"${prefix}is_installed_latest"},
        'list-downloaded'          => {url=>"${prefix}list_downloaded"},
        'list-downloaded-versions' => {url=>"${prefix}list_downloaded_versions"},
        'list-installed'           => {url=>"${prefix}list_installed"},
        'list-installed-versions'  => {url=>"${prefix}list_installed_versions"},
        'list'                     => {url=>"${prefix}list"},
        'update-all'               => {url=>"${prefix}update_all"},
        'update'                   => {url=>"${prefix}update"},
    },
);
Perinci::CmdLineX::CommonOptions::SelfUpgrade->apply_to_object($cli);
$cli->run;

# ABSTRACT: Download and install software
# PODNAME: instopt

__END__

=pod

=encoding UTF-8

=head1 NAME

instopt - Download and install software

=head1 VERSION

This document describes version 0.021 of instopt (from Perl distribution App-instopt), released on 2023-11-20.

=head1 SYNOPSIS

In F<~/.config/instopt.conf>:

 # if not the default ~/software
 download_dir = /home/ujang/software

 # if not the default /opt
 install_dir = !path ~/opt

 # if not the default /usr/local/bin
 program_dir = !path ~/bin

Then:

 # List all installed software in /opt
 % instopt list-installed
 % instopt list-installed -l

 # List installed versions of a software in /opt
 % instopt list-installed-versions firefox

 # Compare installed versions vs downloaded vs latest, for all installed software
 % instopt compare-versions

 # Download a software (e.g. firefox), will be put in $ARCHIVE/f/firefox/<VERSION>/<ARCH>/
 % instopt download firefox

 # Download all known software
 % instopt download-all

 # List all downloaded software
 % instopt list-downloaded
 % instopt list-downloaded -l

 # List downloaded versions of a software
 % instopt list-downloaded-versions firefox
 % instopt list-downloaded-versions -l firefox

 # Update (download + install) a software in /opt
 % instopt update firefox

 # Update all software in /opt
 % instopt update-all

 # Cleanup installed dir (remove inactive versions)
 % instopt cleanup-install-dir

 # Cleanup download dir (remove older versions)
 % instopt cleanup-download-dir


 # Update program to the latest from CPAN
 % instopt --self-upgrade ; # or -U

=head1 DESCRIPTION

B<STATUS:> Early, experimental release. Many things can change without notice.

B<instopt> is an opinionated tool to automate downloading and installing
software binaries (by default to F</opt>, hence the name: "B<inst>all to
/B<opt>"). To describe how it works, I'll describe how I install my software to
F</opt>.

Normally, I depend on the package manager of my OS (Linux distribution) to
install software. But some software need to be updated more often. Let's take as
example B<firefox>, where the OS version is usually too old for my taste. I'll
usually do this:

=over

=item 1.

Go to the Mozilla download page and download the latest firefox binary, let's
say F<firefox-99.1.2.tar.bz2>.

=item 2.

Save this file to F<~/software/f/firefox/99.1.2/linux-x86_64/>, so I can share
this with my other laptops and PC, to avoid redownloading the same stuff.

=item 3.

To install, I do the rest of the steps as root. I extract the tarball to
F</opt/firefox-99.1.2/>.

=item 4.

I create (or update) symlink F</opt/firefox> to point to F</opt/firefox-99.1.2>.

=item 5.

I create (or update) symlink F</usr/local/bin/firefox> to
F</opt/firefox/firefox>.

=back

When a new version of Firefox comes out, I do the following:

=over

=item 1.

Go to the Mozilla website. Download the latest Firefox tarball, e.g.
F<firefox-99.1.3.tar.bz2>.

=item 2.

Save it to F<~/software/f/firefox/99.1.3/linux-x86_64/>.

=item 3.

Extract the tarball to F</opt/firefox-99.1.3>.

=item 4.

Update the symlink F</opt/firefox> to point to F</opt/firefox-99.1.3>.

=item 5.

Optionally delete F</opt/firefox-99.1.2>.

=back

B<instopt> is the tool I wrote to automate the above tasks. Now I only need to
do:

 # instopt update firefox

This will download the latest firefox, save the tarball to the appropriate
location, extract it to F</opt>, and create/update the symlinks.

You can customize the install directory (F</opt>) and the download directory
(F<~/software>).

To start using B<instopt>, first install it from CPAN. Also install the catalog
module for the software that you want/need, e.g. for firefox
L<Software::Catalog::SW::firefox>. This module tells B<instopt> how to find out
the latest version, where the download URL is, and so on.

You might also want to create a configuration file F<~/.config/instopt.conf>
containing:

 # if not the default ~/software
 download_dir = /mnt/shared/software

 # if not the default /opt
 install_dir = /usr/local/opt

After that, install away.

=head1 SUBCOMMANDS

=head2 B<cleanup-download-dir>

Remove older versions of downloaded software.

=head2 B<cleanup-install-dir>

Remove inactive versions of installed software.

=head2 B<compare-versions>

Compare installed vs downloaded vs latest versions of installed software.

=head2 B<download>

Download latest version of one or more software.

=head2 B<download-all>

Download latest version of all known software.

=head2 B<is-downloaded-any>

Check if any version of a software is downloaded.

The download does not need to be the latest version. To check if the latest
version of a software is downloaded, use C<is-downloaded-latest>.


=head2 B<is-downloaded-latest>

Check if latest version of a software has been downloaded.

To only check whether any version of a software has been downloaded, use
C<is-downloaded-any>.


=head2 B<is-installed-any>

Check if any version of a software is installed.

The installed version does not need to be the latest. To check whether the
latest version of a software is installed, use C<is-installed-latest>.


=head2 B<is-installed-latest>

Check if latest version of a software is installed.

To only check whether any version of a software is installed, use
C<is-installed-any>.


=head2 B<list>

List software.

=head2 B<list-downloaded>

List all downloaded software.

=head2 B<list-downloaded-versions>

List all downloaded versions of a software.

=head2 B<list-installed>

List all installed software.

=head2 B<list-installed-versions>

List all installed versions of a software.

=head2 B<update>

Update a software to the latest version.

=head2 B<update-all>

Update all installed software.

=head1 OPTIONS

C<*> marks required options.

=head2 Common options

=over

=item B<--config-path>=I<s>, B<-c>

Set path to configuration file.

Can actually be specified multiple times to instruct application to read from
multiple configuration files (and merge them).


=item B<--config-profile>=I<s>, B<-P>

Set configuration profile to use.

A single configuration file can contain profiles, i.e. alternative sets of
values that can be selected. For example:

 [profile=dev]
 username=foo
 pass=beaver
 
 [profile=production]
 username=bar
 pass=honey

When you specify C<--config-profile=dev>, C<username> will be set to C<foo> and
C<password> to C<beaver>. When you specify C<--config-profile=production>,
C<username> will be set to C<bar> and C<password> to C<honey>.


=item B<--debug>

Shortcut for --log-level=debug.

=item B<--download-dir>=I<s>

(No description)


=item B<--format>=I<s>

Choose output format, e.g. json, text.

Default value:

 undef

Output can be displayed in multiple formats, and a suitable default format is
chosen depending on the application and/or whether output destination is
interactive terminal (i.e. whether output is piped). This option specifically
chooses an output format.


=item B<--help>, B<-h>, B<-?>

Display help message and exit.

=item B<--install-dir>=I<s>

(No description)


=item B<--json>

Set output format to json.

=item B<--log-level>=I<s>

Set log level.

By default, these log levels are available (in order of increasing level of
importance, from least important to most): C<trace>, C<debug>, C<info>,
C<warn>/C<warning>, C<error>, C<fatal>. By default, the level is usually set to
C<warn>, which means that log statements with level C<info> and less important
levels will not be shown. To increase verbosity, choose C<info>, C<debug>, or
C<trace>.

For more details on log level and logging, as well as how new logging levels can
be defined or existing ones modified, see L<Log::ger>.


=item B<--naked-res>

When outputing as JSON, strip result envelope.

Default value:

 0

By default, when outputing as JSON, the full enveloped result is returned, e.g.:

 [200,"OK",[1,2,3],{"func.extra"=>4}]

The reason is so you can get the status (1st element), status message (2nd
element) as well as result metadata/extra result (4th element) instead of just
the result (3rd element). However, sometimes you want just the result, e.g. when
you want to pipe the result for more post-processing. In this case you can use
C<--naked-res> so you just get:

 [1,2,3]


=item B<--no-config>, B<-C>

Do not use any configuration file.

If you specify C<--no-config>, the application will not read any configuration
file.


=item B<--no-env>

Do not read environment for default options.

If you specify C<--no-env>, the application wil not read any environment
variable.


=item B<--page-result>

Filter output through a pager.

This option will pipe the output to a specified pager program. If pager program
is not specified, a suitable default e.g. C<less> is chosen.


=item B<--program-dir>=I<s>

(No description)


=item B<--quiet>

Shortcut for --log-level=error.

=item B<--self-upgrade>, B<-U>

Update program to latest version from CPAN.

=item B<--subcommands>

List available subcommands.

=item B<--trace>

Shortcut for --log-level=trace.

=item B<--verbose>

Shortcut for --log-level=info.

=item B<--version>, B<-v>

Display program's version and exit.

=item B<--view-result>

View output using a viewer.

This option will first save the output to a temporary file, then open a viewer
program to view the temporary file. If a viewer program is not chosen, a
suitable default, e.g. the browser, is chosen.


=back

=head2 Options for subcommand download

=over

=item B<--arch>=I<s>

(No description)


=item B<--software-or-pattern>=I<s@>*

(No description)


Can also be specified as the 1st command-line argument and onwards.

Can be specified multiple times.

=item B<--softwares-or-patterns-json>=I<s>

See C<--software-or-pattern>.

Can also be specified as the 1st command-line argument and onwards.

=back

=head2 Options for subcommand download-all

=over

=item B<--arch>=I<s>

(No description)


=back

=head2 Options for subcommand is-downloaded-any

=over

=item B<--quiet-arg>, B<-q>

(No description)


=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand is-downloaded-latest

=over

=item B<--quiet-arg>, B<-q>

(No description)


=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand is-installed-any

=over

=item B<--quiet-arg>, B<-q>

(No description)


=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand is-installed-latest

=over

=item B<--quiet-arg>, B<-q>

(No description)


=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand list

=over

=item B<--detail>, B<-l>

(No description)


=item B<--downloaded>

If true, will only list downloaded software.

=item B<--installed>

If true, will only list installed software.

=item B<--latest-downloaded>

If true, will only list software which have their latest version downloaded.

If set to true, a software which is not downloaded, or downloaded but does not
have the latest version downloaded, will not be included.

If set to false, a software which has no downloaded versions, or does not have
the latest version downloaded, will be included.


=item B<--latest-installed>

If true, will only list software which have their latest version installed.

If set to true, a software which is not installed, or installed but does not
have the latest version installed, will not be included.

If set to false, a software which is not installed, or does not have the latest
version installed, will be included.


=back

=head2 Options for subcommand list-downloaded

=over

=item B<--arch>=I<s>

(No description)


=item B<--detail>, B<-l>

(No description)


=back

=head2 Options for subcommand list-downloaded-versions

=over

=item B<--arch>=I<s>

(No description)


=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand list-installed

=over

=item B<--detail>, B<-l>

(No description)


=back

=head2 Options for subcommand list-installed-versions

=over

=item B<--software>=I<s>*

(No description)


Can also be specified as the 1st command-line argument.

=back

=head2 Options for subcommand update

=over

=item B<--no-download>

Do not download latest version from URL, just find from download dir.

=item B<--software-or-pattern>=I<s@>*

(No description)


Can also be specified as the 1st command-line argument and onwards.

Can be specified multiple times.

=item B<--softwares-or-patterns-json>=I<s>

See C<--software-or-pattern>.

Can also be specified as the 1st command-line argument and onwards.

=item B<-D>

Shortcut for --no-download.

See C<--no-download>.

=back

=head2 Options for subcommand update-all

=over

=item B<--no-download>

Do not download latest version from URL, just find from download dir.

=item B<-D>

Shortcut for --no-download.

See C<--no-download>.

=back

=head1 COMPLETION

This script has shell tab completion capability with support for several
shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C instopt instopt

in your bash startup (e.g. F<~/.bashrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is recommended, however, that you install modules using L<cpanm-shcompgen>
which can activate shell completion for scripts immediately.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete instopt 'p/*/`instopt`/'

in your tcsh startup (e.g. F<~/.tcshrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is also recommended to install L<shcompgen> (see above).

=head2 other shells

For fish and zsh, install L<shcompgen> as described above.

=head1 CONFIGURATION FILE

This script can read configuration files. Configuration files are in the format of L<IOD>, which is basically INI with some extra features.

By default, these names are searched for configuration filenames (can be changed using C<--config-path>): F</home/u1/.config/instopt.conf>, F</home/u1/instopt.conf>, or F</etc/instopt.conf>.

All found files will be read and merged.

To disable searching for configuration files, pass C<--no-config>.

To put configuration for a certain subcommand only, use a section name like C<[subcommand=NAME]> or C<[SOMESECTION subcommand=NAME]>.

You can put multiple profiles in a single file by using section names like C<[profile=SOMENAME]> or C<[SOMESECTION profile=SOMENAME]> or C<[subcommand=SUBCOMMAND_NAME profile=SOMENAME]> or C<[SOMESECTION subcommand=SUBCOMMAND_NAME profile=SOMENAME]>. Those sections will only be read if you specify the matching C<--config-profile SOMENAME>.

You can also put configuration for multiple programs inside a single file, and use filter C<program=NAME> in section names, e.g. C<[program=NAME ...]> or C<[SOMESECTION program=NAME]>. The section will then only be used when the reading program matches.

You can also filter a section by environment variable using the filter C<env=CONDITION> in section names. For example if you only want a section to be read if a certain environment variable is true: C<[env=SOMEVAR ...]> or C<[SOMESECTION env=SOMEVAR ...]>. If you only want a section to be read when the value of an environment variable equals some string: C<[env=HOSTNAME=blink ...]> or C<[SOMESECTION env=HOSTNAME=blink ...]>. If you only want a section to be read when the value of an environment variable does not equal some string: C<[env=HOSTNAME!=blink ...]> or C<[SOMESECTION env=HOSTNAME!=blink ...]>. If you only want a section to be read when the value of an environment variable includes some string: C<[env=HOSTNAME*=server ...]> or C<[SOMESECTION env=HOSTNAME*=server ...]>. If you only want a section to be read when the value of an environment variable does not include some string: C<[env=HOSTNAME!*=server ...]> or C<[SOMESECTION env=HOSTNAME!*=server ...]>. Note that currently due to simplistic parsing, there must not be any whitespace in the value being compared because it marks the beginning of a new section filter or section name.

To load and configure plugins, you can use either the C<-plugins> parameter (e.g. C<< -plugins=DumpArgs >> or C<< -plugins=DumpArgs@before_validate_args >>), or use the C<[plugin=NAME ...]> sections, for example:

 [plugin=DumpArgs]
 -event=before_validate_args
 -prio=99
 
 [plugin=Foo]
 -event=after_validate_args
 arg1=val1
 arg2=val2

 

which is equivalent to setting C<< -plugins=-DumpArgs@before_validate_args@99,-Foo@after_validate_args,arg1,val1,arg2,val2 >>.

List of available configuration parameters:

=head2 Common for all subcommands


=head2 Configuration for subcommand cleanup-download-dir


=head2 Configuration for subcommand cleanup-install-dir


=head2 Configuration for subcommand compare-versions


=head2 Configuration for subcommand download

 arch (see --arch)
 softwares_or_patterns (see --software-or-pattern)

=head2 Configuration for subcommand download-all

 arch (see --arch)

=head2 Configuration for subcommand is-downloaded-any

 quiet (see --quiet-arg)
 software (see --software)

=head2 Configuration for subcommand is-downloaded-latest

 quiet (see --quiet-arg)
 software (see --software)

=head2 Configuration for subcommand is-installed-any

 quiet (see --quiet-arg)
 software (see --software)

=head2 Configuration for subcommand is-installed-latest

 quiet (see --quiet-arg)
 software (see --software)

=head2 Configuration for subcommand list

 detail (see --detail)
 downloaded (see --downloaded)
 installed (see --installed)
 latest_downloaded (see --latest-downloaded)
 latest_installed (see --latest-installed)

=head2 Configuration for subcommand list-downloaded

 arch (see --arch)
 detail (see --detail)

=head2 Configuration for subcommand list-downloaded-versions

 arch (see --arch)
 software (see --software)

=head2 Configuration for subcommand list-installed

 detail (see --detail)

=head2 Configuration for subcommand list-installed-versions

 software (see --software)

=head2 Configuration for subcommand update

 download (see --no-download)
 softwares_or_patterns (see --software-or-pattern)

=head2 Configuration for subcommand update-all

 download (see --no-download)

=head1 ENVIRONMENT

=head2 INSTOPT_OPT

String. Specify additional command-line options.

=head1 FILES

F<instopt.version> - This file is written in the hardlinked installed software
directory to mark which version the software is. Unlike with symlinking, when
hardlinking there is no straightforward way to know the version.

=head2 /home/u1/.config/instopt.conf

=head2 /home/u1/instopt.conf

=head2 /etc/instopt.conf

=head1 EXAMPLES

=head2 List software that are installed but out-of-date

 % instopt list --installed --nolatest-installed
 
=head2 List software that have been downloaded but out-of-date

 % instopt list --downloaded --nolatest-downloaded
 
=head2 List software that have their latest version downloaded but not installed

 % instopt list --latest-downloaded --nolatest-installed
 
=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-instopt>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-instopt>.

=head1 SEE ALSO

L<swcat> from L<App::swcat>

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 CONTRIBUTING


To contribute, you can send patches by email/via RT, or send pull requests on
GitHub.

Most of the time, you don't need to build the distribution yourself. You can
simply modify the code, then test via:

 % prove -l

If you want to build the distribution (e.g. to try to install it locally on your
system), you can install L<Dist::Zilla>,
L<Dist::Zilla::PluginBundle::Author::PERLANCAR>,
L<Pod::Weaver::PluginBundle::Author::PERLANCAR>, and sometimes one or two other
Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond
that are considered a bug and can be reported to me.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2023, 2021, 2020, 2019, 2018 by perlancar <perlancar@cpan.org>.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-instopt>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=cut
