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

use IPC::Open2;

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


# 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;


# Parse the command line arguments
use CXOpts;
my $class;
my $extension;
my $opt_verbose;
my $opt_help;
my $cxopts=CXOpts->new(["stop_on_non_option"]);
$cxopts->add_options(["class=s"     => \$class,
                      "extension=s" => \$extension,
                      "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;
}
else
{
    my $cmd_count=0;
    $cmd_count++ if ($class);
    $cmd_count++ if ($extension);
    if ($cmd_count>1)
    {
        print STDERR "$name0:error: --extension and --class are mutually exclusive\n";
        $usage = 1;
    }
    elsif ($cmd_count==0)
    {
        print STDERR "$name0:error: One of --extension or --class must be specified\n";
        $usage = 1;
    }
    if (!@ARGV)
    {
        print STDERR "$name0:error: You must specify a command\n";
        $usage = 1;
    }
}


# Print usage
if ($usage)
{
    print STDERR "Usage: $name0 --extension ext command\n";
    print STDERR "or     $name0 --class class command\n";
    print STDERR "or     $name0 --help\n";
    print STDERR "Options:\n";
    print STDERR "   --extension Specifies the extension to associate command with\n";
    print STDERR "   --class     Specifies the class to associate command with\n";
    print STDERR "   command     The command to run for files matching the extension/class,\n";
    print STDERR "               including %1\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";
    exit 2;
}


# Convert the extension to a class
my $wine="$cx_root/bin/wine";
if (!defined $class)
{
    $extension=".$extension" if ($extension !~ /^\./);
    cxlog("Extension = [$extension]\n");

    if (!open2(\*OUT,\*IN,$wine,"regapi.exe","queryValue"))
    {
        print STDERR "$name0:error: Unable to run $wine\n";
        exit 1;
    }

    print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$extension]\n";
    print IN "\"\"\n";
    close IN;
    my $out=(<OUT>)[-1];
    close OUT;
    cxlog("$out");

    if ($out =~ /Value "" = "([^\"]+)"/)
    {
        $class=$1;
    }
    else
    {
        $class="crossover$extension";
        if (!open IN,"|\"$wine\" --wl-app regedit.exe -")
        {
            print STDERR "$name0:error: Unable to run $wine\n";
            exit 1;
        }
        print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$extension]\n";
        print IN "\@=\"$class\"\n";
        close IN;
    }
}


# Delete keys that could get in the way
CXUtils::cxsystem($wine,"--wl-app","regedit.exe","/D","HKEY_LOCAL_MACHINE\\Software\\Classes\\$class\\CLSID");
CXUtils::cxsystem($wine,"--wl-app","regedit.exe","/D","HKEY_LOCAL_MACHINE\\Software\\Classes\\$class\\shell\\Open");


# Associate the class with the specified command
cxlog("Class = [$class]\n");

if (!open IN,"|\"$wine\" --wl-app regedit.exe -")
{
    print STDERR "$name0:error: Unable to run $wine\n";
    exit 1;
}
print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$class]\n";
print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$class\\shell]\n";
print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$class\\shell\\Open]\n";
print IN "[HKEY_LOCAL_MACHINE\\Software\\Classes\\$class\\shell\\Open\\command]\n";
my $cmd="";
foreach my $arg (@ARGV)
{
    $cmd .= " " . ($arg=~/\s/ ? CXUtils::quote_string($arg) : $arg);
}
$cmd.=" \"%1\"" if ($cmd !~ /%1/);
print IN "\@=\"cxnative.exe -- $cmd\"\n";
close IN;

exit 0;
