#!/usr/bin/perl -w
# (c) Copyright 2001-2003. CodeWeavers, Inc.
use strict;

my $name0=$0;
$name0 =~ s+^.*/++;
my $productid="cxoffice";


# Portable which(1) implementation
use Cwd;
sub cxwhich($$)
{
    my $path=$_[0];
    my $app=$_[1];
    if ($app =~ /^\//)
    {
        return $app if (-x $app);
    }
    elsif ($app =~ /\//)
    {
        my $path=cwd . "/$app";
        return $path if (-x $path);
    }
    else
    {
        foreach my $dir (split /:/, $path)
        {
            return "$dir/$app" if ($dir ne "" and -x "$dir/$app");
        }
    }
    return undef;
}

# Locate where CrossOver is installed by looking for the directory
# where this this script is located, unwinding symlinks on the way
my $cx_root;
use File::Basename;
sub locate_cx_root()
{
    return $cx_root if (defined $cx_root);
    $cx_root=$ENV{"CX_ROOT"};
    if (!defined $cx_root)
    {
        my $argv0=cxwhich($ENV{"PATH"},$0);
        $argv0=$0 if (!defined $argv0);
        if ($argv0 =~ m+^[^/]+)
        {
            $argv0=cwd() . "/$argv0";
        }
        my $dir=dirname($argv0);
        while (!-x "$dir/cxtcl")
        {
            last if (!-l $argv0);
            $argv0=readlink($argv0);
            $argv0="$dir/$argv0" if ($argv0 =~ m+^[^/]+);
            $dir=dirname($argv0);
        }
        $dir =~ s%(/\.)*$%%;
        $dir =~ s%(/\./(\./)*)%/%;
        $cx_root=dirname($dir);
    }
    if (!-x "$cx_root/bin/cxtcl")
    {
        my $name0=$0;
        $name0 =~ s+^.*/++;
        print STDERR "$name0:error: could not find CrossOver in \"$cx_root\"\n";
        exit 1;
    }
    $ENV{"CX_ROOT"}=$cx_root;
    return $cx_root;
}

BEGIN {
    push @INC, locate_cx_root() . "/lib/perl";
}
use CXLog;

# Process command-line options
use CXOpts;
my $opt_verbose=1 if (defined $ENV{"CX_LOG"});
my $opt_help;
my $cxopts=CXOpts->new(["stop_on_unknown","stop_on_non_option"]);
$cxopts->add_options(["verbose!"    => \$opt_verbose,
                      "?|h|help"    => \$opt_help
                     ]);
my $err=$cxopts->parse();
CXLog::fdopen(2) if ($opt_verbose);


# Validate the command line options
my $usage;
if ($err)
{
    print STDERR "$name0:error: $err\n";
    $usage=2;
}
elsif ($opt_help)
{
    $usage=2;
}


# Print usage
if ($usage)
{
    print STDERR "Usage: $name0 [--help] [--verbose] [browser_options] [url]\n";
    print STDERR "Options:\n";
    print STDERR "   --verbose       Print more information about what is going on\n";
    print STDERR "   --help,-h       Shows this help message\n";
    print STDERR "   browser_options can be any options supported by your browser\n";
    print STDERR "   url             represents the URL you want to open, if any\n";
    exit 2;
}


# Convert the arguments
sub process_arg($)
{
    my $arg=$_[0];

    if ($arg =~ m%^\w+://%)
    {
        $arg =~ s+ +%20+g;
    }
    elsif (-e $arg)
    {
        $arg =~ s+ +%20+g;
        $arg =  getcwd() . "/$arg" if ($arg !~ m+^/+);
        $arg =  "file://localhost/$arg";
    }
    return $arg;
}

my @args;
cxlog("Argument conversion:\n");
foreach my $arg (@ARGV)
{
    my $parg=process_arg($arg);
    cxlog("  [$arg] -> [$parg]\n");
    push @args,$parg;
}


# Import the CrossOver settings
use CXConfig;
my $cxconfig          = CXConfig->new("$cx_root/etc/$productid.conf",
                                      "$ENV{HOME}/.$productid/$productid.conf");
my $preferred_browser = $cxconfig->get("CrossOver","PreferredBrowser");


# Pick the browsers
my @browser_list;
if ($preferred_browser)
{
    @browser_list=($preferred_browser);
}
else
{
    # It seems that gnome-moz-remote sometimes returns without doing anything.
    # So I put it last.
    push @browser_list,$ENV{BROWSER} if (defined $ENV{BROWSER});
    push @browser_list,("skipstone", "galeon", "MozillaFirebird", "mozilla",
                        "netscape",
                        "konqueror",
                        "opera",
                        "gnome-moz-remote");
}


# Start the browser
cxlog("Starting browser:\n");
foreach my $browser_cmd (@browser_list)
{
    my @browser=CXUtils::cmdline2argv($browser_cmd);
    my $browser_path=cxwhich($ENV{PATH},$browser[0]);
    if (defined $browser_path and -s $browser_path)
    {
        cxlog("  trying '",join("' '",@browser,@args),"'\n");
        exec @browser, @args;
    }
    else
    {
        cxlog("  skipping $browser_cmd\n");
    }
}
print STDERR "$name0:error: could not find a Linux browser (the following were tried: @browser_list)\n";
exit 1;
