#!/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;
use CXUtils;


# Process command-line options
use CXOpts;
my $bottle=$ENV{"CX_BOTTLE"} || "dotwine";
my $arg_app;
my $ux_app;
my $cx_app;
my $wl_app;
my $opt_wait;
my $opt_check;
my $workdir;
my $opt_convert=1;
my $opt_display;
my $opt_allow_root;
my $opt_untrusted;
my $opt_verbose=1 if (defined $ENV{"CX_LOG"});
my $opt_cx_log;
my $opt_debugmsg=$ENV{"CX_DEBUGMSG"};
my $opt_dashdash;
my $opt_managed;
my $opt_dll;
my $opt_winver;
my $opt_version;
my $opt_help;
my $cxopts=CXOpts->new(["stop_on_unknown","stop_on_non_option"]);
$cxopts->add_options(["bottle=s"    => \$bottle,
                      "ux-app=s"    => \$ux_app,
                      "cx-app=s"    => \$cx_app,
                      "wl-app=s"    => \$wl_app,
                      "wait"        => \$opt_wait,
                      "workdir=s"   => \$workdir,
                      "convert!"    => \$opt_convert,
                      "display=s"   => \$opt_display,
                      "check"       => \$opt_check,
                      "allow-root!" => \$opt_allow_root,
                      "untrusted!"  => \$opt_untrusted,
                      "verbose!"    => \$opt_verbose,
                      "cx-log=s"    => \$opt_cx_log,
                      "debugmsg=s"  => \$opt_debugmsg,
                      ""            => \$opt_dashdash,
                      "managed"     => \$opt_managed,
                      "dll=s"       => \$opt_dll,
                      "winver=s"    => \$opt_winver,
                      "version"     => \$opt_version,
                      "?|h|help"    => \$opt_help
                     ]);
my $err=$cxopts->parse();
if ($opt_verbose)
{
    CXLog::fdopen(2);
    $opt_cx_log="-" if (!defined $opt_cx_log);
}

sub check_security_patch()
{
    my $maptest = "$ENV{CX_ROOT}/bin/cxmaptest";

    if (-x $maptest && CXUtils::cxsystem($maptest))
    {
        my $rc=CXUtils::message(
            "-title","Error",
            "-buttons","Ok",
            "-default","Ok",
            "-image","data/crossover.xpm",
            "Your system appears to contain a security patch that " .
            "will cause trouble when running some programs in CrossOver. ".
            "To fix the problem, please consult the online FAQ at ".
            "http://crossover.codeweavers.com/docs/office/html/troubleshooting.html");
        return 1;
    }
    return 0;
}

# Validate the command line options
my $usage;
if ($err)
{
    print STDERR "$name0:error: $err\n";
    $usage=2;
}
elsif ($opt_help)
{
    $usage=2;
}
elsif ($opt_version)
{
    $usage=3;
}
else
{
    if (!defined $opt_cx_log)
    {
        $opt_cx_log = "-";
        $opt_debugmsg="-all" if (!defined $opt_debugmsg);
    }
    elsif ($opt_cx_log eq "/dev/null" and !defined $ux_app)
    {
        # No point sending traces to /dev/null
        $opt_debugmsg = "-all";
    }

    $ENV{"DISPLAY"}=$opt_display if (defined $opt_display);
    $ENV{"CX_DEBUGMSG"}=$opt_debugmsg if (defined $opt_debugmsg);
    $ENV{"CX_ALLOW_ROOT"}=$opt_allow_root if (defined $opt_allow_root);

    my $cmd_count=0;
    $cmd_count++ if (defined $ux_app);
    $cmd_count++ if (defined $cx_app);
    $cmd_count++ if (defined $wl_app);
    $cmd_count++ if (defined $opt_wait);
    if ($cmd_count>1)
    {
        print STDERR "$name0:error: --cx-app, --ux-app, --wl-app and --wait are mutually exclusive\n";
        $usage = 1;
    }
    elsif ($cmd_count == 0)
    {
        if ($name0 ne "wine")
        {
            $arg_app=$name0;
        }
        else
        {
            if (!@ARGV)
            {
                if ($opt_check)
                {
                    exit check_security_patch();
                }
                print STDERR "$name0:error: you must specify an application to run\n";
                $usage=1;
            }
            elsif (!$opt_dashdash and @ARGV > 1 and $ARGV[1] eq "--")
            {
                splice @ARGV, 1, 1;
            }
        }
    }
}

# Check the WINEPREFIX ownership
sub check_wine_prefix_ownership()
{
    if (!-o $ENV{"WINEPREFIX"})
    {
        my $rc=CXUtils::message(
            "-title","Error",
            "-buttons","Ok",
            "-default","Ok",
            "-image","data/crossover.xpm",
            "The Wine environment ($ENV{WINEPREFIX}) does not belong to you. " .
            "Please check the value of \$HOME and/or use 'su -'.");
        exit 1;
    }
}

# Check if libc is using NPTL threads
sub is_nptl()
{
    my $glibc_check = "$ENV{CX_ROOT}/bin/cxglibc-check";
    my $threads = `\"$glibc_check\" -t` || "unknown";

    if (CXLog::is_on())
    {
        system("\"$glibc_check\" 1>&2");
    }
    if ($threads =~ /linuxthreads-tls/)
    {
        # check glibc version, we only want to use nptl on glibc >= 2.3
        open VERSION, "/lib/libc.so.6 2>/dev/null |";
        while (<VERSION>)
        {
            if (/GNU C Library.*version 2\.(\d+)/)
            {
                $threads = "nptl" if ($1 >= 3);
                last;
            }
        }
        close VERSION;
    }
    return $threads =~ /nptl/;
}

# Setup the environment
if (!$ENV{CX_INITIALIZED})
{
    # Read the settings
    use CXConfig;
    my $cxconfig=CXConfig->new("$ENV{CX_ROOT}/etc/$productid.conf",
                               "$ENV{HOME}/.$productid/$productid.conf");

    # Locate the bottle
    my $wine_prefix;
    if ($bottle =~ m%^/%)
    {
        $wine_prefix=$bottle;
        if (!-d $wine_prefix)
        {
            print STDERR "$name0:error: the specified bottle does not exist\n";
            exit 1;
        }
        $bottle =~ s%^.*/%%;
    }
    elsif ($bottle =~ m%/%)
    {
        $wine_prefix=cwd() . "/$bottle";
        if (!-d $wine_prefix)
        {
            print STDERR "$name0:error: the specified bottle does not exist\n";
            exit 1;
        }
        $bottle =~ s%^.*/%%;
    }
    else
    {
        $wine_prefix="$ENV{HOME}/.$productid/$bottle";
    }
    my @updater_cmd;
    if (-r "$wine_prefix/cxbottle.conf")
    {
        $cxconfig->read("$wine_prefix/cxbottle.conf");
        my $updater=$cxconfig->get("Bottle","Updater");
        if ($updater)
        {
            cxlog("Mode = 'multi-user, non-root'\n");
            @updater_cmd=($updater,$wine_prefix);
        }
        else
        {
            cxlog("Mode = 'skeleton, non-root'\n");
            # check if an update is required
            my $mtime_ref=(stat("$cx_root/support/templates/$bottle/cxbottle.conf"))[9];
            my $mtime_bottle=(stat("$wine_prefix/cxbottle.conf"))[9];
            if (!$mtime_ref or !$mtime_bottle or $mtime_bottle <= $mtime_ref)
            {
                @updater_cmd=("$cx_root/support/templates/$bottle/setup/setup",
                              $wine_prefix);
            }
        }
    }
    elsif (-d $wine_prefix)
    {
        if (-d "$cx_root/support/$bottle")
        {
            cxlog("Mode = '< 2.0 multi-user, non-root'\n");
            $cxconfig->read("$cx_root/support/$bottle/cxbottle.conf");
            my $updater=$cxconfig->get("Bottle","Updater");
            if (!$updater)
            {
                print STDERR "$name0:error: 'Updater' is not set in '$cx_root/support/$bottle/cxbottle.conf'. Maybe '$wine_prefix' is a stale multi-user directory?\n";
                exit 1;
            }
            @updater_cmd=($updater,$wine_prefix);
        }
        else
        {
            cxlog("Mode = '< 2.0 skeleton, non-root'\n");
            @updater_cmd=("$cx_root/support/templates/$bottle/setup/setup",
                          $wine_prefix);
        }
    }
    elsif (-w "$cx_root/support/$bottle")
    {
        cxlog("Mode = 'single-user or multi-user running as root'\n");
        $wine_prefix="$cx_root/support/$bottle";
        $cxconfig->read("$wine_prefix/cxbottle.conf");

        # if root, warn about affecting all users
        if ($> == 0 and !$ENV{"CX_ALLOW_ROOT"} and !$wl_app and !$ux_app)
        {
            my $rc=CXUtils::message(
                "-title","CrossOver Warning",
                "-buttons","Continue:0,Abort:2",
                "-default","Abort",
                "-image","data/crossover.xpm",
                "You are about to run or install a Windows application as root.\n" .
                "\n" .
                "Note that any change you make while doing so " .
                "will impact all other users. In some cases it may also " .
                "prevent the application from running correctly in " .
                "regular user accounts.\n" .
                "\n" .
                "Click on 'Abort' to stop the launch process now, " .
                "or 'Continue' to run the above Windows application.\n");
            exit 1 if ($rc != 0);
            $ENV{"CX_ALLOW_ROOT"}="1";
        }

        # check if an update is required
        my $mtime_ref=(stat("$cx_root/support/templates/$bottle/cxbottle.conf"))[9];
        my $mtime_bottle=(stat("$wine_prefix/cxbottle.conf"))[9];
        if (!$mtime_ref or !$mtime_bottle or $mtime_bottle <= $mtime_ref)
        {
            @updater_cmd=("$cx_root/support/templates/$bottle/setup/setup",
                          $wine_prefix);
        }
    }
    elsif (-d "$cx_root/support/$bottle")
    {
        cxlog("Mode= 'multi-user, new non-root user'\n");
        $cxconfig->read("$cx_root/support/$bottle/cxbottle.conf");
        my $updater=$cxconfig->get("Bottle","Updater");
        if (!$updater)
        {
            print STDERR "$name0:error: 'Updater' is not set in '$cx_root/support/$bottle/cxbottle.conf'.\n";
            exit 1;
        }
        @updater_cmd=($updater,$wine_prefix);
    }
    else
    {
        cxlog("Mode = 'skeleton, new user'\n");
        $cxconfig->read("$cx_root/support/templates/$bottle/cxbottle.conf");
        @updater_cmd=("$cx_root/support/templates/$bottle/setup/setup",
                      $wine_prefix);

        # if root, warn
        if ($> == 0 and !$ENV{"CX_ALLOW_ROOT"})
        {
            my $rc=CXUtils::message(
                "-title","CrossOver Warning",
                "-buttons","Continue:0,Abort:2",
                "-default","Abort",
                "-image","data/crossover.xpm",
                "You are about to run a Windows application as root.\n" .
                "Note that any application you install as root will only\n" .
                "be usable by root.\n" .
                "\n" .
                "Click on 'Abort' to stop the launch process now, " .
                "or 'Continue' to run the above Windows application.\n");
            exit 1 if ($rc != 0);
            $ENV{"CX_ALLOW_ROOT"}="1";
        }
    }

    my $bin_path   = $cxconfig->get("Wine","BinPath") || "$cx_root/bin";
    my $lib_path   = $cxconfig->get("Wine","LibPath") || "$cx_root/lib";
    my $dll_path   = $cxconfig->get("Wine","DllPath") ||
                      join( ":", map { $_ .= "/wine"; } split( /:/, $lib_path ));
    my $ld_preload = $cxconfig->get("Wine","LDPreload") || "";
    my $ld_assume_kernel = $cxconfig->get("Wine","LDAssumeKernel");

    $ENV{CX_ROOT}=$cx_root;
    $ENV{CX_BOTTLE}=$wine_prefix;
    $ENV{WINEPREFIX}=$wine_prefix;
    $ENV{CX_WINDOWS_VERSION}=$opt_winver if (defined $opt_winver);
    $ENV{PATH}="$bin_path" . (defined $ENV{PATH}?":$ENV{PATH}":"");
    $ENV{LD_PRELOAD}=$ld_preload;
    $ENV{LD_ASSUME_KERNEL}=$ld_assume_kernel if (defined $ld_assume_kernel);
    $ENV{WINELOADER}=cxwhich($bin_path,"wineloader");
    $ENV{WINESERVER}=cxwhich($bin_path,"wineserver");
    delete $ENV{WINEOPTIONS};

    if (is_nptl())
    {
        # Add nptl prefix to lib and dll paths
        $dll_path = join( ":", (map { $_ = "$_/nptl"; } split( /:/, $lib_path )), split( /:/, $dll_path ));
        $lib_path = join( ":", map { $_ = "$_/nptl:$_"; } split( /:/, $lib_path ));
    }
    $ENV{LD_LIBRARY_PATH}="$lib_path" . (defined $ENV{LD_LIBRARY_PATH}?":$ENV{LD_LIBRARY_PATH}":"");
    $ENV{WINEDLLPATH}="$dll_path" . (defined $ENV{WINEDLLPATH}?":$ENV{WINEDLLPATH}":"");

    # And create / update / upgrade the bottle if necessary
    check_wine_prefix_ownership() if (-e $wine_prefix);
    if (@updater_cmd)
    {
        cxlog("Updating the WinePrefix directory:\n");
        if (CXUtils::cxsystem(@updater_cmd))
        {
            CXUtils::message(
                "-title","CrossOver Warning",
                "-buttons","Ok:0",
                "-default","Ok",
                "-image","data/crossover.xpm",
                "An error occurred during the WINEPREFIX ($wine_prefix) " .
                "creation / update. This application may fail to start.\n");
            if (!-d $wine_prefix)
            {
                print STDERR "$name0:error: WINEPREFIX ($wine_prefix) does not exist\n";
                exit 1;
            }
        }
        check_wine_prefix_ownership();
    }
    if ( !defined $ENV{"CXOFFICE_DRIVE_TYPE_HACK"})
    {
        $ENV{"CXOFFICE_DRIVE_TYPE_HACK"} = "hd";
    }
}
if (CXLog::is_on())
{
    cxlog("Inherited ") if ($ENV{CX_INITIALIZED});
    cxlog("Environment:\n");
    foreach my $name (qw(CX_ROOT CX_BOTTLE WINEPREFIX CX_WINDOWS_VERSION
                         PATH LD_LIBRARY_PATH WINEDLLPATH LD_PRELOAD
                         LD_ASSUME_KERNEL WINELOADER WINESERVER WINEOPTIONS
                         CX_LOG CX_DEBUGMSG))
    {
        cxlog("  $name = ",(defined $ENV{$name}?"\"$ENV{$name}\"":"<undefined>"),"\n");
    }
}
$ENV{CX_INITIALIZED}="1";


# Print usage (requires that the environment be setup)
if ($usage)
{
    if ($usage==3)
    {
        system($ENV{WINELOADER},"--version");
        exit 0;
    }
    print STDERR "Usage: $name0 [--help] [--cx-log filename] [--verbose]\n";
    print STDERR "            [--cx-app application|--wl-app application|--ux-app application]\n";
    print STDERR "            [--check] [--display display] [--workdir dir]\n";
    print STDERR "            [wine options]\n";
    print STDERR "Options:\n";
    print STDERR "   --cx-log  Sends debugging output to the specified file.\n";
    print STDERR "             If 'filename' ends with '.z', '.gz' or '.bz2' the file\n";
    print STDERR "             will be compressed with compress, gzip or bzip2 respectively\n";
    print STDERR "             By default debugging output is turned off\n";
    print STDERR "   --cx-app  Specifies the name of a Windows executable to run\n";
    print STDERR "   --wl-app  Specifies the name of a Winelib executable to run\n";
    print STDERR "   --ux-app  Specifies the name of a Unix executable to run\n";
    print STDERR "   --check   Check that Wine's environment is sane\n";
    print STDERR "   --display Sets the X display as specified\n";
    print STDERR "   --workdir Change the current directory as specified\n";
    print STDERR "   --verbose Print more information about what is going on\n";
    print STDERR "   --help,-h Shows this help message and the Wine options\n";
    if ($usage == 2)
    {
        print STDERR "\n";
        system($ENV{WINELOADER},"--help");
        exit 0;
    }
    exit 2;
}

if ($opt_check)
{
    check_security_patch();
}
if ($opt_wait)
{
    # If exec fails we will get an error message and a return code of 2
    exec $ENV{"WINESERVER"}, "-w";
}

# Search for the application
my $cmd;
my @wine_args;
if (defined $ux_app)
{
    $cmd=$ux_app;
}
else
{
    $cmd=$ENV{WINELOADER};
    push @wine_args,"--dll",$opt_dll if (defined $opt_dll);
    push @wine_args,"--managed" if (defined $opt_managed);
    push @wine_args,"--debugmsg",$opt_debugmsg if (defined $opt_debugmsg);
    push @wine_args,"--";

    if (defined $arg_app)
    {
        # Use the name we were invoked as, to find either a WineLib
        # application, or a Windows executable
        $arg_app .= ".exe" unless ($arg_app =~ /\.exe$/i);
        $wl_app = cxwhich($ENV{"WINEDLLPATH"}, "$arg_app.so");
        if (!defined $wl_app)
        {
            # We could not find a Winelib application so we assume it
            # is a Windows executable.
            $cx_app=$arg_app;
        }
    }

    if (defined $cx_app)
    {
        my $c_root="$ENV{WINEPREFIX}/fake_windows";
        my $app_path;
        if ($cx_app =~ /^[a-zA-Z]:/ )
        {
            $app_path=$cx_app;
        }
        elsif ($cx_app =~ /\.(com|exe)$/i)
        {
            $app_path=`find "$c_root/" -iname "$cx_app" 2>/dev/null`;
        }
        else
        {
            $app_path=`find "$c_root/" -iname "$cx_app.exe" 2>/dev/null`;
            if (!$app_path)
            {
                $app_path=`find "$c_root/" -iname "$cx_app.com" 2>/dev/null`;
            }
        }
        chomp $app_path;
        if ($app_path eq "")
        {
            print STDERR "$name0:error: could not find $cx_app in\n";
            print STDERR "              \"$c_root\"\n";
            print STDERR "              Is it installed?\n";
            exit 2;
        }
        elsif ($app_path =~ /\n/)
        {
            print STDERR "$name0:error: multiple matches found for $cx_app in\n";
            print STDERR "              \"$c_root\"\n";
            exit 2;
        }
        unshift @wine_args, "winewrapper.exe", $productid;
        unshift @ARGV, $app_path;
    }
    elsif (defined $wl_app)
    {
        my $exe_name = $wl_app;
        if ($exe_name =~ /\.exe$/)
        {
            $exe_name .= ".so";
        }
        elsif ($exe_name !~ /\.exe\.so$/)
        {
            $exe_name .= ".exe.so";
        }
        $exe_name = cxwhich( $ENV{"WINEDLLPATH"}, $exe_name );
        if (!defined $exe_name)
        {
            print STDERR "$name0:error: could not find $wl_app in\n";
            print STDERR "              \"$ENV{WINEDLLPATH}\"\n";
            exit 2;
        }
        unshift @ARGV, $exe_name;
    }
    else
    {
        unshift @wine_args, "winewrapper.exe", $productid;
    }

    if (!defined $wl_app)
    {
        if ($opt_untrusted)
        {
            my $tmp=$ENV{TMPDIR} || "/tmp";
            if ($ARGV[0] =~ m%^\Q$tmp\E(/.*)$%)
            {
                my $rc=CXUtils::message(
                    "-title","CrossOver Security Warning",
                    "-buttons","Continue:0,Abort:2",
                    "-default","Abort",
                    "-image","data/crossover.xpm",
                    "You are about to run a Windows application that " .
                    "appears to come from an untrusted source (most likely " .
                    "an email attachement):\n" .
                    "\n" .
                    "$ARGV[0]\n" .
                    "\n" .
                    "If this is a virus, running it could put your " .
                    "computer at risk.\n" .
                    "Click on 'Abort' to stop the launch process before any " .
                    "harm has been done, or 'Continue' to run the above " .
                    "Windows application.\n");
                exit 1 if ($rc != 0);
            }
        }
        CXUtils::cxsystem("$ENV{WINELOADER}","--debugmsg","-all","cxmn.exe");
    }
}

# Setup the logging
my $log;
use FileHandle;
if ($opt_cx_log ne "-")
{
    my $zipper;

    if ($opt_cx_log =~ /\.gz$/)
    {
        $zipper = "gzip -9";
    }
    elsif ($opt_cx_log =~ /\.bz2$/)
    {
        $zipper = "bzip2 -9";
    }
    elsif ($opt_cx_log =~ /\.z$/)
    {
        $zipper = "compress";
    }
    else
    {
        $zipper = undef;
    }

    if ($zipper)
    {
        $log=FileHandle->new("| exec $zipper -c >\"$opt_cx_log\"");
    }
    else
    {
        $log=FileHandle->new($opt_cx_log,"w");
    }
    print STDERR "$name0:error: unable to open the log file: $!\n" if (!$log);
}


# Convert the arguments
sub winepath(@)
{
    my $pid=open(PIPE,"-|");
    return undef if (!defined $pid);
    if ($pid==0)
    {
        my @loader=($ENV{"WINELOADER"});
        push @loader,"--debugmsg",$opt_debugmsg if (defined $opt_debugmsg);
        push @loader,"--";
        if ($log)
        {
            # Redirect stderr
            open STDERR, ">&=" . $log->fileno();
            my $tmp=select STDERR; $| = 1; select $tmp; # Make unbuffered
        }
        if ($log or CXLog::is_on())
        {
            print STDERR "\n** ",scalar(localtime(time)),"\n";
            print STDERR "Starting '",join("' '",@loader),"'\n";
            print STDERR "'winepath.exe' '",join("' '",@_),"'\n\n";
        }
        exec @loader,"winepath.exe",@_
        or print STDERR "$name0:error: unable to start winepath\n";
        exit 1;
    }
    my @res=<PIPE>;
    close PIPE;
    return @res;
}

my @args;
my $uworkdir;
if (defined $ux_app or !$opt_convert)
{
    # Pass the arguments as is
    @args=@ARGV;
}
else
{
    # Convert the arguments: Unix -> Windows
    # Invoking winepath is relatively slow
    # so we try to do it only if necessary
    my @wp_indices;
    my @wp_args=("--long","--");
    foreach my $arg (@ARGV)
    {
        if ($arg =~ /:switch:/ or $arg =~ /~W[BS]~/)
        {
            # This argument comes from Windows so there is no need to
            # convert it.
            # "~WS~" corresponds to '/' and "~WB~" to '\'
            # ':switch:' is for backward compatibility
            $arg =~ s+:switch:+/+g;
            $arg =~ s+~WS~+/+g;
            $arg =~ s+~WB~+\\+g;
        }
        elsif (-e $arg)
        {
            push @wp_indices,scalar(@args);
            push @wp_args,$arg;
        }
        push @args,$arg;
    }
    if (@wp_indices)
    {
        @wp_args=winepath(@wp_args);
        if (@wp_args == @wp_indices)
        {
            for (my $i=0;$i<@wp_indices;$i++)
            {
                if ($wp_args[$i] ne "\n")
                {
                    chomp $wp_args[$i];
                    $args[$wp_indices[$i]]=$wp_args[$i];
                }
            }
        }
        else
        {
            print STDERR "$name0:error: the arguments conversion failed ",
                  scalar @wp_args,"!=",scalar @wp_indices,"\n";
            for (my $i=0;$i<@wp_args;$i++)
            {
                print STDERR "wp_args[$i] = '$wp_args[$i]'\n";
            }
        }
    }
    if (CXLog::is_on())
    {
        cxlog("Argument conversion:\n");
        for (my $i=0;$i<@args;$i++)
        {
            cxlog("  [$ARGV[$i]] -> [$args[$i]]\n");
        }
    }

    # Convert the workdir: Windows -> Unix
    if (defined $workdir and $workdir ne "")
    {
        ($uworkdir)=winepath("--unix","--",$workdir);
        chomp $uworkdir;
        cxlog("Workdir conversion:\n");
        cxlog("  [$workdir] -> [$uworkdir]\n");
    }
}


# Start Wine
if ($> == 0)
{
    # Files created in the multi-user master directory must be world readable
    umask(umask() & ~0055);
}
if (defined $uworkdir and !chdir($uworkdir))
{
    print STDERR "$name0:warning: unable to chdir to '$uworkdir': $!\n";
}
cxlog("Command:\n");
cxlog("$cmd @wine_args @args\n");
if ($log)
{
    # Redirect stderr
    open STDERR, ">&=" . $log->fileno();
    my $tmp=select STDERR; $| = 1; select $tmp; # Make unbuffered
    $log->close();
}
if ($log or CXLog::is_on())
{
    print STDERR "\n** ",scalar(localtime(time)),"\n";
    print STDERR "Starting '$cmd' '",join("' '",@wine_args),"'\n";
    print STDERR "'",join("' '",@args),"'\n\n";
}

exec $cmd, @wine_args, @args
or print "$name0:error: unable to start '$cmd': $!\n";
exit 1;
