package Pcore::Nginx v1.1.2;

use Pcore -dist, -class, -try;

# TODO eval
# use Pcore::GeoIP;

has data_dir     => ( is => 'ro',   isa => Str, default => "$ENV->{DATA_DIR}" );
has nginx_bin    => ( is => 'lazy', isa => Str, default => 'nginx' );
has nginx_prefix => ( is => 'lazy', isa => Str, default => '/etc/nginx/' );

has conf_dir  => ( is => 'lazy', isa => Str,    init_arg => undef );
has vhost_dir => ( is => 'lazy', isa => Str,    init_arg => undef );
has proc      => ( is => 'ro',   isa => Object, init_arg => undef );

sub _build_conf_dir ($self) {
    my $conf_dir = $self->data_dir . 'nginx/';

    P->file->mkpath($conf_dir);

    return $conf_dir;
}

sub _build_vhost_dir ($self) {
    my $vhost_dir = $self->conf_dir . 'vhost/';

    P->file->mkpath($vhost_dir);

    return $vhost_dir;
}

sub run ($self) {
    my $params = {
        pid                => $self->conf_dir . 'nginx.pid',
        mime_types         => $ENV->share->get('/data/nginx/mime.types'),
        error_log          => $self->data_dir . 'nginx-error.log',
        geoip_country_path => $ENV->share->get('/data/geoip_country.dat'),
        geoip_city_path    => $ENV->share->get('/data/geoip_city.dat'),
        vhost_dir          => $self->vhost_dir,
        ssl_dhparam        => $ENV->share->get('/data/nginx/dhparam-4096.pem'),
    };

    P->file->write_text( $self->conf_dir . 'conf.nginx', { mode => q[rw-r--r--] }, P->tmpl( type => 'text' )->render( 'nginx/conf.nginx', $params ) );

    P->file->write_text( $self->conf_dir . 'ssl.nginx', { mode => q[rw-r--r--] }, P->tmpl( type => 'text' )->render( 'nginx/ssl.nginx', $params ) );

    P->pm->run_proc(
        [ $self->nginx_bin, '-c', $self->conf_dir . 'conf.nginx' ],
        on_ready => sub ($proc) {
            $self->{proc} = $proc;

            return;
        }
    );

    return;
}

sub add_vhost ( $self, $name, $cfg ) {
    P->file->write_bin( $self->vhost_dir . "$name.nginx", $cfg );

    return;
}

1;
__END__
=pod

=encoding utf8

=head1 NAME

Pcore::Nginx - Pcore nginx application

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 SEE ALSO

=head1 AUTHOR

zdm <zdm@cpan.org>

=head1 CONTRIBUTORS

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by zdm.

=cut
