#!/usr/bin/perl -w
=head1	NAME

command_doc - Scripting system commands in an OpenOffice.org document

=head1	SYNOPSIS

This sample script triggers an external program each time a given string
is found in a given OpenOffice.org Writer document

usage : command_doc filename -command "command" -trigger "trigger_string"

The "command" option is executed using the shell (so it depends on the
target program name and the operating system)
If the command is successful, the search string is replaced by "PASSED";
in case of failure, there is no replacement

The main goal of this small program is to demonstrate the possibility
to control a business process with the content of an OpenOffice.org
document.

=cut

use OpenOffice::OODoc;
use Getopt::Long;

my $command	= undef;
my $trigger	= undef;
my $count	= 0;
my $verbose	= undef;
my $save_file	= undef;

# command execution subroutine, assuming the return code of the command
# is 0 if OK, or -1 (or any nonzero value) if not
sub	executeCommand
	{
	my $found_text	= shift;
		# conditional trace message
	$verbose && print "Found $found_text !\n";
		# count the occurences
	$count++;
		# execute the command & get the system return code
	my $result = system($command);
		# return something or nothing according to the return code
	return $result == 0 ? "PASSED" : undef;
	}

# get the command line parameters
GetOptions
	(
	'command=s'	=> \$command,
	'trigger=s'	=> \$trigger,
	'verbose'	=> \$verbose,
	'save'		=> \$save_file
	);
my $filename	= $ARGV[0];

die "usage : command_doc filename -command cmd -trigger trigger_string\n"
	unless ($command && $trigger && $filename);

# create an OpenOffice.org text object from the file
my $doc	= ooText(file => $filename);
die "$filename is unavailable or is not an OpenOffice.org document\n"
	unless $doc;

# execute the command each time $trigger is found in the text
# in case of failure, 'executeCommand' returns 'undef', so there is
# no replacement
$doc->replaceAll($trigger, \&executeCommand);

# final trace message
$verbose && print "The expression $trigger has been found $count time(s)\n";

# append an execution report as a new paragraph at the end of
# the OpenOffice.org document, and commit the changes
if ($save_file)
	{
	my $time_string = localtime();
	$doc->appendParagraph
		(
		text	=> "Processed by command_doc at $time_string",
		style	=> "Text body"
		);
	$doc->save;
	}

exit;