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

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;

# Strings to match in the autorun.inf DisplayNames field.
# Matching will be case-sensitive.
my @display_names=
("msoffice97"   => "Microsoft\\s+(Office|Word|Excel|PowerPoint|Access)\\s+97",
 "msoffice2000" => "Microsoft\\s+(Office|Word|Excel|PowerPoint|Access)\\s+2000",
 "msofficexp"   => "Microsoft\\s+(Office|Word|Excel|PowerPoint|Access)\\s+XP",
 "msoffice"     => "Microsoft\\s+(Office|Word|Excel|PowerPoint|Access)",
 "Photoshop"    => "Photoshop",
 "Quicken"      => "Quicken"
);

# Specifies a list of greps to perform. Each line is of the form
# ["<product>", "<file-glob>", ["<regexp1>","<regexp2>",...]]
# Where
#  <product>    is the product code
#  <file-glob>  specifies a case-insensitive file glob
#  <regexpX>    specifies a list of case-sensitive regular expressions
#               (use '((?i)case-insensitive)' where needed). For a file
#               to match it must match all specified regular expressions.
#               If none is specified (i.e. if that field is 'undef'), then
#               the file merely has to exist to match.
my @grep_specs=
(["Photoshop",    "Autoplay/*.ini", ["Photoshop"]],
 ["Visio",        "autorun.inf",    ["Visio"]],
 ["Quicken",      "autorun/*.ini",  ["Quicken"]],
 ["Dreamweaver",  "autorun.inf",    ["dw_mx.ico"]],
 ["msofficexp",   "owc10.msi",      undef],
 ["msoffice97",   "Off97*.inf",     undef],
#["project2002",  "msproj10.cab",   undef],
#["publisher2002","pub.msi",        undef],
#["visio2003",    "visio.msi",      undef],
#["vstudio6",     "vb98*1.inf",     undef], # Visual Basic
#["vstudio6",     "vc98*1.inf",     undef], # Visual C++
#["vstudio6",     "vf98*1.inf",     undef], # Visual FoxPro
#["vstudio6",     "vj98*1.inf",     undef], # Visual J++
#["vstudio6",     "vs98ent.mif",    undef], # Visual Studio
#["vstudio.net",  "vs_setup.msi",   undef],
 ["QuickBooks",   "cd.dat",         ["SKU=CDPRO","QuickBooks"]],
 ["Lotus Notes",  "autorun.inf",    ["\\bLotus\\b\\W*\\bNotes\\b"]]
#["HalfLife",     "readme.txt",    ["Half-Life","Sierra"]]
);

my $dir;


# Utility functions

sub case_desensitize($)
{
    my $str=$_[0];
    $str=~ s/([a-z])/[\l$1\u$1]/gi;
    return $str;
}

# We assume that we will read only a few directories,
# so it's reasonable to keep them all in a cache.
my %glob_cache;
sub get_files($)
{
    my $pattern=$_[0];
    if (!$glob_cache{$pattern})
    {
        my $glob=case_desensitize($pattern);
        my @files=glob("$dir/$glob");
        cxlog("  $glob -> @files\n");
        $glob_cache{$pattern}=\@files;
    }
    return $glob_cache{$pattern};
}

# We assume that we will read only a few relatively small files,
# so it's reasonable to keep them all in a cache.
my %file_cache;
sub read_file($)
{
    my $filename=$_[0];
    if (!$file_cache{$filename})
    {
        my @lines=();
        if (open FILE, $filename)
        {
            @lines=<FILE>;
            close FILE;
        }
        $file_cache{$filename}=\@lines;
    }
    return $file_cache{$filename};
}

sub file_grep($$)
{
    my $lines=$_[0];
    my $regexps=$_[1];

    my $match=1;
    if ($regexps)
    {
        foreach my $regexp (@$regexps)
        {
            if (!grep /$regexp/,@$lines)
            {
                $match=0;
                last;
            }
        }
    }
    return $match;
}

sub multi_grep($$)
{
    my $file_pattern=$_[0];
    my $regexps=$_[1];

    cxlog("$file_pattern\n");
    my $files=get_files($file_pattern);
    if (!@$files)
    {
        cxlog("  file not found\n");
        return 0;
    }
    if (!$regexps)
    {
        cxlog("  file found\n");
        return 1;
    }

    foreach my $file (@$files)
    {
        my $lines=read_file($file);
        cxlog("  $file [\"",join("\",\"",@$regexps),"\"]\n");
        return 1 if (file_grep($lines,$regexps));
    }
    return 0;
}


# Process command-line options
use CXOpts;
my $opt_verbose;
my $opt_help;
my $cxopts=CXOpts->new(["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;
}
else
{
    if (@ARGV != 1)
    {
        print STDERR "$name0:error: you must specify a file or directory path\n";
        $usage=1;
    }
    else
    {
        $dir=$ARGV[0];
        $dir=dirname($dir) if (-f $dir);
    }
}


# Print usage
if ($usage)
{
    print STDERR "Usage: $name0 path/to/cd\n";
    exit 2;
}


# Find and read the autorun.inf file
for (my $i=0;$i<@display_names;$i+=2)
{
    my $regexp="^\\s*((?i)DisplayName)\\s*=\\s*$display_names[$i+1]";
    if (multi_grep("autorun.inf",[$regexp]))
    {
        print "$display_names[$i]\n";
        exit 0;
    }
}

foreach my $grep_spec (@grep_specs)
{
    cxlog("\n@$grep_spec[0]:\n");
    if (multi_grep(@$grep_spec[1],@$grep_spec[2]))
    {
        print "@$grep_spec[0]\n";
        exit 0;
    }
}

print "other\n";
exit 0;
