package Search::Glimpse::Server;

use warnings;
use strict;

use Search::Glimpse::ConfigData;
use base 'Exporter';

our $VERSION = '0.01';

=encoding UTF-8

=head1 NAME

Search::Glimpse::Server - Perl interface to start Glimpse server.

=head1 SYNOPSIS

  use Search::Glimpse::Server

  my $server = Search::Glimpse::Server->new( index => '/path/to/indexes/folder',
                                             post  => 2001,
                                             host => 'localhost' );
  $server->start;

=head1 DESCRIPTION

This is a Perlish interface to glimpseserver binary. You should create
a C<Glimpse::Server> object with the desired configuration, and then
B<start> the server. Future versions might track on whether the server
is running or not, and give a chance to stop it.

=head2 Available Methods

=over 4

=item C<new>

Constructor. Has three optional arguments:

=over 4

=item C<index>

A path to the folder where C<glimpseindex> stored its indexes.

=item C<port>

The port where the server will run (defaults to 2001);

=item C<host>

The host where the server is running (that is, localhost, usually);

=back

=cut

sub new {
    my ($class, %ops) = @_;

    my $self = {
                bin => Search::Glimpse::ConfigData->config('glimpseserver')
               };
    $self->{host}  = $ops{host}  if exists $ops{host};
    $self->{port}  = $ops{port}  if exists $ops{port};
    $self->{index} = $ops{index} if exists $ops{index};

    return bless $self => $class;
}

=item C<start>

Starts C<glimpseserver>.

=cut

sub start {
    my $self = shift;

    die "Indexes folder ($self->{index}) does not exist\n" unless -d $self->{index};

    my $commandline = join (" ",
                            $self->{bin},
                            exists($self->{index})?"-H $self->{index}":"",
                            exists($self->{host} )?"-J $self->{host}" :"",
                            exists($self->{port} )?"-K $self->{port}" :"");


    $ENV{LC_ALL} = 'C';
    my $output;
    open PIPE, "-|", $commandline or die "Can't execute glimpseserver";
    $output = join "" => <PIPE>;
    close PIPE;

    $self->{output} = $output || "";
    return $self;
}

=back

=head1 SEE ALSO

perl(1)

=head1 AUTHOR

Alberto Manuel Brandão Simões, E<lt>ambs@cpan.orgE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011 by Alberto Manuel Brandão Simões

=cut

!0;
