#! /usr/bin/env perl
# PODNAME: cpangit-server
our $VERSION = '0.011'; # VERSION
# ABSTRACT: serve a CPAN tree from a git branch, or all CPAN trees in the git repo

use FindBin;
BEGIN { push @INC, "$FindBin::RealBin/../lib" if -f "$FindBin::RealBin/../dist.ini" }
use Mojolicious::Lite;
use CPAN::InGit::Server;
use CPAN::InGit::TerminalEscape;
use Getopt::Long;
use Pod::Usage;
use Log::Any::Adapter;
use v5.36;


my $git_dir= $ENV{GIT_DIR};
my $base_path= '/';
my %mount_options;
my $max_download_size= 100 << 20;
my $max_cache_size= 10 << 30;
{
   local $Getopt::Long::config= Getopt::Long::ConfigDefaults();
   Getopt::Long::Configure(qw( no_permute pass_through no_auto_abbrev ));
   GetOptions(
      'git-dir=s'        => \$git_dir,
      'path-base=s'      => \$base_path,
      'base-path|p=s'    => \$base_path,
      'tree|t=s'         => \$mount_options{archive_tree},
      'branch-head-only' => \$mount_options{branch_head_only},
      'serve-tags'       => \$mount_options{serve_tags},
      'serve-commits'    => \$mount_options{serve_commits},
      'index-branches'   => \$mount_options{index_branches},
      'browse-dists'     => \$mount_options{browse_dists},
      'allowed-upstreams:s' => sub { CPAN::InGit->update_allowed_upstreams($_[1]) },
      'tree-cache-limit=i' => \$mount_options{tree_cache_limit},
      'max-download-size=s' => sub { $max_download_size= CPAN::InGit::_parse_size($_[1]) },
      'max-cache-size=s' => sub { $max_cache_size= CPAN::InGit::_parse_size($_[1]) },
      'max-files=i'      => \$CPAN::InGit::MutableTree::archive_limits{max_files},
      'max-total-size=s' => sub { $CPAN::InGit::MutableTree::archive_limits{max_total_size}= CPAN::InGit::_parse_size($_[1]) },
      'max-file-size=s'  => sub { $CPAN::InGit::MutableTree::archive_limits{max_file_size}= CPAN::InGit::_parse_size($_[1]) },
      'help|h'           => sub { pod2usage(1) },
   ) or pod2usage(2);
}
@ARGV= qw( daemon -m production )
   unless @ARGV;

# Log messages include paths requested by clients
CPAN::InGit::TerminalEscape->apply(\*STDOUT, \*STDERR);
Log::Any::Adapter->set( MojoLog => logger => app->log );

die "No such GIT_DIR directory: '$git_dir'\n"
   if defined $git_dir && !-d $git_dir;

my $git_repo= Git::Raw::Repository->discover($git_dir // '.');
my $cpan_repo= CPAN::InGit->new(git_repo => $git_repo);
$cpan_repo->useragent->max_response_size($max_download_size);
$cpan_repo->download_limit($max_cache_size);

# If user wants a single tree, resolve the name
if (defined $mount_options{archive_tree}) {
   my $name= $mount_options{archive_tree};
   # Anonymous clients must not see or change the working directory and index
   my $atree= $cpan_repo->get_archive_tree($name, use_workdir => 0)
      or croak($cpan_repo->lookup_tree($name)
              ? "Tree '$name' does not look like an ArchiveTree"
              : "Unknown git tree '$name'");
   $mount_options{archive_tree}= $atree;
}

# The routes for the server controller can be mounted at any sub-path desired.
# By default, this mounts every possible Git tree which looks like a valid ArchiveTree layout
# so you can point cpanm to `-M host:/BRANCH_NAME` or `-M host:/SHA-1` or `-M host:/GIT_TAG`
CPAN::InGit::Server->mount(app->routes->any($base_path), $cpan_repo, app => app, %mount_options);

app->start;

__END__

=pod

=encoding UTF-8

=head1 NAME

cpangit-server - serve a CPAN tree from a git branch, or all CPAN trees in the git repo

=head1 USAGE

  # Serve all trees
  cpangit-server [--git-dir=PATH] [OPTIONS] MOJO_COMMAND...
  
  # Serve one branch
  cpangit-server --tree=BRANCH_NAME [OPTIONS] MOJO_COMMAND...

This command acts as a CPAN file server, either serving all the repo's branches (and tags and
SHA-1 hashes) or serving a single specified branch.  OPTIONS are described below. MOJO_OPTIONS
control how the server is launched, and are described by `mojo --help`.

Friendly paths such as C</feature/demo/> resolve the shortest existing selector,
preferring branches over tags and commit IDs at each boundary. Explicit paths
C</~branch/feature~demo/>, C</~tag/feature~demo/>, and C</~commit/SHA1/>
select one namespace unambiguously. Slashes in ref names are encoded as C<~>.

=head1 OPTIONS

=over

=item --git-dir=PATH

Path to the Git repository of L<CPAN::InGit>.  The default is GIT_DIR from the environment,
or any git repo above "."

=item --path-base=PATH  (-p PATH)

Base URL from which to serve the branches or single tree.  Default is '/'.

=item --tree=BRANCH_OR_TAG_OR_SHA1 (-t BRANCH)

Serve only a single Git tree from the root path.

=item --serve-tags

When serving all branches, also serve the trees of tags, like C<< /~tag/v1.0/ >> or
C<< /v1.0/ >>.  By default only the current head of each branch is served.

Each tree served is kept in a cache (see C<--tree-cache-limit>) along with its parsed package
index, which is around 15MB for a mirror of all of CPAN, and any client can request any tag.
If clients request more distinct trees than the cache holds, they evict each other, and every
request has to load and parse a package index again.

=item --serve-commits

When serving all branches, also serve the tree of any commit, like C<< /~commit/SHA1/ >> or
C<< /SHA1/ >> (or an abbreviation of it).  By default only the current head of each branch is
served.

This has the same cost as C<--serve-tags>, but every commit in the history of the repository
can be requested, so it is easy for a client to keep the cache full of trees nobody else uses,
and make the server parse a package index on every request.  This should probably only be used
on trusted networks.

=item --branch-head-only

Deprecated; this is now the default.  Overrides C<--serve-tags> and C<--serve-commits>.

=item --index-branches

Show links to available local CPAN archive branches on the repository's index page.
Disabled by default.  This has no effect when serving a single tree with C<--tree>.

=item --tree-cache-limit=COUNT

The number of Git trees to keep loaded in memory, each with its parsed package index (around
15MB for a mirror of all of CPAN).  C<0> means no limit.  By default there is no limit when
only branches are served, because the cache never holds more than one tree per branch.
The default is 20 when C<--serve-tags> or C<--serve-commits> are used.
(see L<CPAN::InGit::Server/tree_cache_limit>)

=item --allowed-upstreams=URL1,URL2,...

=item --allowed-upstreams=+URL1,URL2,...

The upstream URLs which mirror branches may download from.  The default is the public CPAN by
https (www.cpan.org, cpan.org, cpan.metacpan.org and backpan.perl.org).  The list replaces the
default, unless it begins with C<+>, in which case the URLs are added to it.  An empty list
prevents downloading from any upstream.  The C<upstream_url> of a mirror is configured in its
branch, which might have come from someone else's repository, so this lets you decide which
hosts may be contacted.  (see L<CPAN::InGit/allowed_upstreams>)

A branch whose C<upstream_url> is not allowed is served without downloading anything.

=item --browse-dists

Allow browsing the files of each distribution, and comparing two distributions, through URLs
beneath the archive file name.  Disabled by default.  The first such request for a
distribution unpacks it into the dist cache repository, which uses disk space and CPU time at
the request of any client, within the limits below.
(see L<CPAN::InGit::Server/Distribution Contents>)

Do not use this when facing un-trusted networks if you are also mirroring an external URL; an
attacker could trigger downloads of unlimited upstream packages and use unlimited disk space.

=item --max-cache-size=SIZE

The total size of the files the server may download from upstreams (for mirror branches with
autofetch) before it stops downloading.  The default is 10G, and C<0> means no limit.  SIZE is
a number of bytes with an optional suffix of C<K>, C<M> or C<G>.

The server doesn't commit what it downloads: it writes the files to the repository as objects
which no branch refers to, and serves them for as long as it runs.  So this limits the disk
space and bandwidth that clients can make each server process use.  When the limit is reached, a request for a file which would have to be downloaded gets C<503 Service
Unavailable> (and a mirror whose package index is out of date keeps serving the old one) until
the server is restarted.  Files already in the branches are served as usual.  The limit applies
to each process, so a server with several worker processes may download that much in each.

To keep files which were downloaded, add them to a branch with C<cpangit-add>.  The objects
the server wrote are removed by C<git gc> once they are older than its prune time (two weeks
by default; see C<gc.pruneExpire> in L<git-config(1)>).  The server never runs C<git gc>
itself, because pruning immediately could remove objects that another command has written but
not yet committed.

=item --max-download-size=SIZE

The largest file that will be downloaded from the upstream of a mirror.  The default is 100M,
which may exclude some of the larger CPAN modules.  SIZE is a number of bytes with an optional
suffix of C<K>, C<M> or C<G>.

=item --max-files=COUNT

=item --max-total-size=SIZE

=item --max-file-size=SIZE

Limits for unpacking a distribution archive to browse or compare it: the number of files, the
total uncompressed size, and the size of the largest file.  C<0> means no limit.  The defaults
are 40000 files, 200M total, and 30M per file.  An archive which exceeds a limit is remembered
in the dist cache, and not unpacked again unless the server restarts with a higher limit.
(see L<CPAN::InGit::MutableTree/import_from_archive>)

=back

=head1 VERSION

version 0.011

=head1 AUTHOR

Michael Conrad <mike@nrdvana.net>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by Michael Conrad, and IntelliTree Solutions.

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

=cut
