#!/usr/bin/env perl

# This script has three uses:
# 1. From the command line to install straight into a given directory:
#    bin/ooinstall /opt/Foo
# 2. From the command line to link into a given directory:
#    bin/ooinstall -l /opt/FooLinked
# 3. When packaging (called from package-ooo), to install to DESTDIR

use File::Find;
use Cwd;

%setup_vars = ();

$path = '';
$linked='';

sub suck_setup($)
{
    my $file = shift;
    if (-f $file) {
	print "Reading setup from $file\n";
	open ($Vars, "bash -c '. $file ; set'|") || die "Can't find $file: $!";
	while (<$Vars>) {
	    /([^=]*)=(.*)/ || next;
	    $setup_vars{$1} = $2;
	}
	close ($Vars);
	return 1;
    }
    return 0;
}

( $^O =~ /openbsd/i ) || ( $^O =~ /darwin/i ) || ( -f "/proc/meminfo" ) || die "The installer cannot work without javaldx running, which requires /proc to be mounted";

suck_setup ("./setup") || suck_setup ("bin/setup") || die "can't find bin/setup";

for $arg (@ARGV) {
    if ($arg eq '-l') {
	$linked = '-l';

    } elsif ($arg eq '-h' || $arg eq '--help') {
	$help = 1;
    } else {
	$path = $arg;
    }
}

$help = 1 if $path eq '';

if ($help) {
    print "ooinstall [-l] <prefix to install to>\n";
    print "  -l - performs a linkoo on the installed source\n";
    exit 1;
}

$sources_path=Cwd::realpath($setup_vars{'OOBUILDDIR'});

# Call the solenv/bin/ooinstall
# Note we need to export those here, as solenv/bin/ooinstall can't use $setup_vars and needs to get them from $ENV
system ("cd $sources_path ; . ./*Set.sh ; export OOO_LANGS_LIST=$setup_vars{'OOO_LANGS_LIST'}; export OODESTDIR=$setup_vars{'OODESTDIR'}; export OOO_STRIP=$setup_vars{'OOO_STRIP'}; solenv/bin/ooinstall $linked $path") && die "Failed to ooinstall";

print "Installing extra dictionaries...\n";
system ("cd $setup_vars{TOOLSDIR}/bin ; " .
	"sh ./install-dictionaries $path/basis$setup_vars{VERSION}/share/dictionaries") && die "Failed to install dictionaries: $!";

print "Building galleries...\n";
system ("cd $setup_vars{TOOLSDIR}/bin ; " .
       	"sh ./build-galleries $path") && die "Failed to build extra galleries: $!";

system ("cd $setup_vars{TOOLSDIR}/bin ; " .
       	"sh ./install-mono $path") && die "Failed to finish mono installation: $!";
