#!/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:p:hs', \%switch);


sub start {
    say "starting repo";
    daemonize();

    my $packages = packages($switch{d});
    my $base_dir = $switch{d} || $ENV{HOME}; $base_dir =~ s/(.*?)(\/deb)/$1/;

    unlink( "$base_dir/Packages", "$base_dir/Packages.gz" );
    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 && gzip Packages");

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

sub usage {
    say "\nUsage:\n\tstart:\trepo -d /path/to/deb";
    say "\thelp\trepo -h";
    say "\n\n";
}


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

=head1 NAME repo

Creates Packages list and starts repository on localhost:3000

=head1 SYNOPSIS

repo creates Packages.gz file needed by APT client to read content of repository, then starts repository running on Mojolicious server on localhost:3000

=head1 USAGE

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

usage:                  C<repo -h>

=cut



