=head1 NAME

OpenOffice

=head1 SYNOPSIS

  use OpenOffice;
  OpenOffice->converter({"source" => "/tmp/source.sxw",
                         "target" => "/home/httpd/vhosts/otm/paul.pdf"});

=head2 DESCRIPTION

  Global OpenOffice process program

  Errors are FATAL, to protect against that you need to eval me!

=head3 target

   Must be a full system path of where to put the resulting file.

=head3 source

   Must be a full system path.  Should be a zipped openoffice file.
   I will convert it to a .pdf.
   does not return anything
   if the target exists, I will immediately exit, so 
   make sure your target is available!

   This module is to enable the ORDERLY processing of documents
   on the system.  Only one openoffice program should be running
   at any time, and this module will enforce that.  

   Please use this module whenever you need to make a .pdf document!

=cut

package OpenOffice;

use strict;
no strict 'refs';

sub converter {

    my ($self,$options) = @_;
    umask 000;
    use File::Copy;
    use Fcntl ':flock';
    open SEMAPHORE, "> /tmp/oakbox.oolock" or die "1$!";
    flock SEMAPHORE, LOCK_EX or die "2 $!";

    if($options->{source} eq ""){ die "no source set on openoffice convert"; }
    if($options->{target} eq ""){ die "no target set on openoffice convert"; }

# to stop those button pressing monkeys, close immediately if
# the target file exists!

    my $target = $options->{target};
    if(-e $target){ close SEMAPHORE; return(); }

 my @elements =  split(/\./,$options->{target});
  # use last element to determine ending file type!
    
  my $convertto = "PDF";
  my $outputextension = "pdf";  

if($elements[-1] eq "doc"){ $convertto = "DOC"; $outputextension = "doc"; }

# Convert that puppy
    $ENV{DISPLAY} ||= ':5';
    umask 000;

    if (system('nice','-n','3','/usr/bin/soffice', '-invisible', "macro:///Standard.Module1.ConvertTo$convertto($options->{source})") != 0) { die "OO doc convert $options->{source} failed\n"; }

    my @elements =  split(/\./,$options->{source});

    $elements[-1] = $outputextension;
    my $moveme      = join('.',@elements);
    move($moveme, $options->{target})  or die "Cannot move $moveme \nto\n target: $options->{target}\n $!";

    close SEMAPHORE;
    return();
}

1;