#!/usr/bin/perl

use strict;
use warnings;

use lib './lib';
use setup;
use lib $setup{libdir};

use File::Spec;

use UNIVERSAL::require;
use Getopt::Long;

use GLPI::Agent::Daemon::Win32;

# Load dedicated .rc file if present. Sample one, if renamed, permits
# to log stdout and stderr for early debugging purpose
do __FILE__ . ".rc" if (!@ARGV && -e __FILE__ . ".rc");

Getopt::Long::Configure( "no_ignorecase" );

my %options = ();

unless (GetOptions(
    \%options,
    'register',
    'delete',
    'name|n=s',
    'displayname|d=s',
    'libdir|l=s',
    'program|p=s',
    'help'
)) {
    Pod::Usage->use();
    pod2usage(-verbose => 0);
}

if ($options{help}) {
    Pod::Usage->use();
    pod2usage(-verbose => 0, -exitstatus => 0);
}

my $progfile  = File::Spec->rel2abs( __FILE__ );
my $directory = File::Spec->rel2abs( '..', $progfile );

our %setup;

my $ret = 0;

my $service = GLPI::Agent::Daemon::Win32->new( %setup )
    or die "Can't create service object: $!";

if ($options{register}) {

    $ret = $service->RegisterService(
        program     => $progfile,
        %options
    );
    print "'", $service->displayname(), "' registred as ", $service->name()," service\n"
        unless $ret;

} elsif ($options{delete}) {
    $ret = $service->DeleteService(%options);
    print $service->name(), " service deleted\n"
        unless $ret;

} else {
    # on Win2k, Windows do not chdir to the bin directory
    # we need to do it by ourself
    chdir($directory);

    # Under newer win32 releases, setting accepted controls may be required
    $service->AcceptedControls();

    # Just start the service
    $service->StartService();
}

exit($ret);

__END__

=head1 NAME

glpi-win32-service - GLPI perl Agent service for Windows

=head1 SYNOPSIS

glpi-win32-service [--register|--delete|--help] [options]

  Options are only needed to register or delete the service. They are handy
  while using GLPI perl agent from sources.

  Register options:
    -n --name=NAME                  unique system name for the service
    -d --displayname="Nice Name"    display name of the service
    -l --libdir=PATH                full path to agent perl libraries use it if
                                    not found by the script
    -p --program="path to program"  perl script to start as service

  Delete options:
    -n --name=NAME                  unique system name of the service to delete

  Samples to use from sources base:
    perl bin/glpi-win32-service --help
    perl bin/glpi-win32-service --register
    perl bin/glpi-win32-service --delete
    perl bin/glpi-win32-service --register -n glpi-agent-test -d "[TEST] GLPI Agent Service"
    perl bin/glpi-win32-service --delete -n glpi-agent-test
