#!/usr/bin/perl -w
#
# ooffice - Wrapper script for OpenOffice.org
#

# Define system installation directory
my $SystemInstallDir = '/usr/lib/openoffice';
# Suffix for parallel installable versioning
my $BinSuffix = '';
# ooo-build version
my $OOO_BUILDVERSION = '2.0.4.9';

if ($SystemInstallDir =~ /^@/) {
    $SystemInstallDir = '/usr/lib/ooo-2.0';
    $BinSuffix = '';
}

my $Binary = 'soffice';
if (-x "$SystemInstallDir/program/ooqstart") {
    $Binary = 'ooqstart';
    $ENV{OOO_EXTRA_ARG} ||= '';
}

my @ooo_argv;
my $widgets_set;
while ($ARGV[0]) {
    $_ = shift;
    if (m/^--widgets-set/) {
	$widgets_set = shift;
	(defined $widgets_set) || die "Error: The option --widgets-set requires a value\n" .
	                            "For example: --widgets-set gtk\n";
    } elsif (m/^--version/) {
	print "This is OpenOffice.org built with ooo-build-$OOO_BUILDVERSION\n";
	exit 0;
    } elsif (m/^-(base|calc|draw|impress|math|web|writer)$/ && $Binary eq "ooqstart") {
        $ENV{OOO_EXTRA_ARG} = $_;
    } elsif (m/^-fromtemplate$/ && $Binary eq "ooqstart") {
        $ENV{OOO_EXTRA_ARG} = "slot:5500";
    } else {
        push @ooo_argv, $_;
    }
}

if (!@ooo_argv) {
    my $arg;
    if ($0 =~ m/\/oo(calc|draw|impress|math|web|writer|base)$BinSuffix$/) {
        $arg = "-$1";
    } elsif ($0 =~ m/\/oofromtemplate$BinSuffix$/) {
        $arg = "slot:5500";
    }

    if ($arg) {
        if ($Binary eq "soffice") {
            push @ooo_argv, "$arg";
	} else {
	    $ENV{OOO_EXTRA_ARG} = $arg;
	}
    }
}

if (defined $widgets_set) {
    $ENV{SAL_USE_VCLPLUGIN} = $widgets_set;
}

# FIXME: the following two fixes should be done by OOo itself
# create the user config directory  with safe rights 700 if it we find
# the right path and the directory does not exist
if (open BOOTSTRAPRC, "$SystemInstallDir/program/bootstraprc") {
    while (my $line = <BOOTSTRAPRC>) {
	chomp $line;
    	if (($line =~ m/^\s*UserInstallation\s*=\s*([^\s]*)\s*$/) && ($1)) {
	    my $userConfDir=$1;
	    $userConfDir =~ s|\$SYSUSERCONFIG|$ENV{HOME}|;
	    $userConfDir =~ s|file://||;
	    mkdir ($userConfDir,0700) unless (-d $userConfDir);
	    last;
	}
    }
    close BOOTSTRAPRC;
}
# touch ~/.recently-used with safe rights 700 if it does not exist
if (! -f "$ENV{HOME}/.recently-used") {
    open (RECENTLY_USED, ">$ENV{HOME}/.recently-used") &&
    close RECENTLY_USED &&
    chmod 0600, "$ENV{HOME}/.recently-used";
}
	
if (!(-f '/proc/version')) {
    print STDERR "\n\n --- Warning - OO.o will not work without a mounted /proc filesystem --- \n\n\n";
}

# And here we go.
exec "$SystemInstallDir/program/$Binary", @ooo_argv
