#!/usr/bin/env perl

use 5.010;
use warnings;
use strict;

use Mojolicious::Lite;
use File::Find;
use File::Path;
use Getopt::Std;
use App::Repo::Daemon qw< daemonize >;
use App::Repo qw< digest packages >;
use open qw<:encoding(UTF-8)>;

my %switch = ();
$0 = "repo";
getopts('d:hp', \%switch);


sub start {

    my $packages = packages($switch{d});
    my $base_dir = $switch{d}; $base_dir =~ s/(\/deb)//;

    system("rm -rf $base_dir/Packages*");
    open(my $fh,">>", "$base_dir/Packages") || die "cant open $base_dir/Packages: $!";
    
    for my $package (@$packages){
        for(@$package){
            print $fh "$_\n";
        }
    };
    close $fh;
    system("cd $base_dir && cp Packages Packages.txt && gzip Packages");

    my $repo_icon_path = sub {
        my $repo_lib_dir = `perldoc -l App::Repo`; chomp $repo_lib_dir;
        $repo_lib_dir =~ s/\.pm/\/CydiaIcon\.png/;
        return $repo_lib_dir;
    };
    
    my $repo_icon = $repo_icon_path->();
    unless( -f "$base_dir/CydiaIcon.png" ){
        system("cp $repo_icon $base_dir/");
    }

    if( defined $switch{p} ){ say "refreshed"; return }

    say "starting repo";

    daemonize();

    app->static->paths->[0] = $base_dir;
    any '/' => sub {
        shift->reply->static('Packages.txt');
    };

    app->start('daemon');

#plugin( 'Directory', root => "$base_dir" )->start('daemon', '-l', "http://*:3000");
}

sub usage {
    say "\nUsage:\n\tstart:\t\t\trepo -d /path/to/deb";
    say "\trefresh packages\trepo -d ~/path/to/deb -p"; 
    say "\thelp:\t\t\trepo -h";
    say "\tdocumentation:\t\tperldoc repo";
    say "\n\n";
}


if(defined $switch{d}){
    start();
} elsif(defined $switch{h}){
    usage();
} 

=head1 NAME

repo - Creates list of Debian packages and starts APT repository on localhost:3000.

=head1 DESCRIPTION 

'repo' creates MD5, SHA1 and SHA256 hashes of each package in 'deb' directory, checks control file and use it to create Packages.gz file needed by APT client to read content of repository, then starts repository running on Mojolicious server ( localhost:3000 ). 'repo' has dependency on 'curl', it's using it to download perl implementation of 'ar' archiver on first run which is saved into C<$HOME/tmp/.repo> directory.

See GIF at L<https://github.com/z448/repo>

=head1 OPTIONS

Pass full path to 'deb' directory containing Debian packages with -d parameter. Repo will generate 'Packages.gz' file in a same directory where 'deb' is located. 

start:                  C<repo -d /path/to/deb>

refresh packages:       C<repo -d /path/to/deb -p>

usage:                  C<repo -h>

=head1 AUTHOR

Zdenek Bohunek E<lt>zed448@icloud.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2016 by Zdenek Bohunek

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

=cut

