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

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


my $cx_root;
BEGIN {
    $cx_root=$ENV{CX_ROOT};
    push @INC, "$cx_root/lib/perl";
}
use CXLog;
use CXUtils;
use CXConfig;
use CXUpgrade;

my $template_dir="$cx_root/support/templates/dotwine";


#####
#
# Bottle creation
#
#####

sub create_bottle($)
{
    my $updater=$_[0];

    # Get the bottle defaults
    my $cxconfig=CXConfig->new("$cx_root/etc/$productid.conf");
    # If it's not a multi-user bottle, then read the user's settings
    $cxconfig->read("$ENV{HOME}/.$productid/$productid.conf") if ($updater);

    # Copy the files
    my $parent=$ENV{"CX_BOTTLE"};
    $parent=~s%/[^/]*$%%;
    CXUtils::cxsystem("mkdir","-p",$parent);
    CXUtils::cxsystem("cp","-r",$template_dir,$parent);
    CXUtils::cxsystem("rm","-rf","$ENV{CX_BOTTLE}/setup");
    CXUtils::cxsystem("chmod","-R","u+w,a+r",$ENV{CX_BOTTLE});
    CXUtils::cxsystem("find \"$ENV{CX_BOTTLE}\" -name \"*.exe\" -exec chmod a+x {} \\;");
    CXUtils::cxsystem("find \"$ENV{CX_BOTTLE}\" -type d -exec chmod a+x {} \\;");

    # Tweak the cxbottle.conf configuration file
    my $src=CXUpgradeConfig->new(undef);
    my $dst=CXUpgradeConfig->new("$template_dir/cxbottle.conf");
    if (defined $dst)
    {
        # Tweak the configuration values
        my $s;

        $s=$src->add("Bottle");
        $s->set("BottleID",CXUtils::get_wine_dir_id($ENV{"CX_BOTTLE"}));
        $s->set("Updater",$updater) if (defined $updater);
        my $menu_root=$cxconfig->get("BottleDefaults","MenuRoot");
        $s->set("MenuRoot",$menu_root) if (defined $menu_root);

        # Do the final merge and write the new configuration file
        $dst->merge($src);
        $dst->write("$ENV{CX_BOTTLE}/cxbottle.conf");
    }

    # Tweak the Wine configuration file
    $src=CXUpgradeConfig->new(undef);
    $dst=CXUpgradeConfig->new("$template_dir/config");
    if (defined $dst)
    {
        $dst->{quote}="\"";

        # Tweak the configuration values
        my $s;

        my $outlook=$cxconfig->get("BottleDefaults","OutlookSecurity");
        if ($outlook)
        {
            $outlook=$cxconfig->get("BottleDefaults","BlockedExtensions");
            $s=$src->add("AppDefaults\\\\OUTLOOK.EXE");
            $s->set("DenyShellExecute",$outlook);

            # Do the final merge and write the new configuration file
            $dst->merge($src);
            $dst->write("$ENV{CX_BOTTLE}/config");
        }
    }

    # And finally, add the drives to the Wine configuration file
    CXUtils::cxsystem("$cx_root/bin/cxsetup","--setup");

    # Update the registry
    my $my_docs=$cxconfig->get("BottleDefaults","MyDocumentsDir");
    if (!defined $my_docs)
    {
        foreach ("$ENV{HOME}/My Documents","$ENV{HOME}/Documents","$ENV{HOME}")
        {
            if (-d $_)
            {
                $my_docs=$_;
                last;
            }
        }
    }
    $my_docs=`\"$cx_root/bin/wine\" --no-convert --wl-app winepath.exe --long -- \"$my_docs\"`;
    if (open FD,"| \"$cx_root/bin/wine\" --wl-app regedit.exe -")
    {
        chomp $my_docs;
        $my_docs=CXUtils::escape_string($my_docs);
        print FD "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders]\n";
        print FD "\"Personal\"=\"$my_docs\"\n";
        print FD "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders]\n";
        print FD "\"Personal\"=\"$my_docs\"\n";
        close FD;
    }

    my $proxy_host=$cxconfig->get("BottleDefaults","HttpProxyHost");
    my $proxy_port=$cxconfig->get("BottleDefaults","HttpProxyPort") || "8080";
    if (defined $proxy_host)
    {
        if (open FD,"| \"$cx_root/bin/wine\" --wl-app regedit.exe -")
        {
            print FD "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings]\n";
            print FD "\"ProxyEnable\"=\"dword:1\"\n";
            print FD "\"ProxyServer\"=\"http=$proxy_host:$proxy_port\"\n";
            print FD "[HKEY_USERS\\.Default\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings]\n";
            print FD "\"ProxyEnable\"=\"dword:1\"\n";
            print FD "\"ProxyServer\"=\"http=$proxy_host:$proxy_port\"\n";
            close FD;
        }
    }
    else
    {
        if (open FD,"| \"$cx_root/bin/wine\" --wl-app regedit.exe -")
        {
            print FD "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings]\n";
            print FD "\"ProxyEnable\"=\"dword:0\"\n";
            print FD "[HKEY_USERS\\.Default\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings]\n";
            print FD "\"ProxyEnable\"=\"dword:0\"\n";
            close FD;
        }
    }
}


#####
#
# Bottle upgrade
#
#####

sub upgrade_cxbottle($)
{
    my $opt_old_version=$_[0];

    my $filename="$ENV{CX_BOTTLE}/cxbottle.conf";
    cxlog("\n** Upgrading $filename\n\n");
    my $src=CXUpgradeConfig->new($filename);
    $src=CXUpgradeConfig->new(undef) if (!defined $src);
    my $s=$src->get("Bottle");
    my $old_version;
    if (defined $s)
    {
        $old_version=$s->get("Version") || "2.0.0";
        $old_version=~s/[^0-9.].*$//;
    }
    else
    {
        $old_version=$opt_old_version || "1.3.1";
    }
    cxlog("Old Version=$old_version\n");

    my $backup="$filename.$old_version";
    if (-f $filename and !-f $backup and !copy($filename,$backup))
    {
        print STDERR "$name0:warning: unable to write backup to $backup: $!\n";
    }

    my $template="$template_dir/cxbottle.conf";
    my $dst=CXUpgradeConfig->new($template);
    if (!defined $dst)
    {
        print STDERR "$name0:error: unable to read $template: $!\n";
        return $old_version;
    }

    # Tweak the configuration values
    my $bottleid;
    $s=$src->get("Bottle");
    if (defined $s)
    {
        # Reset the Version field
        $s->remove_field("Version");
        $bottleid=$s->get("BottleID");
    }
    if (!defined $bottleid)
    {
        # Make sure the bottle gets an id
        # (in case of an upgrade from a pre-2.0 tree)
        $s=$src->add("Bottle");
        $s->set("BottleID",CXUtils::get_wine_dir_id($ENV{"CX_BOTTLE"}));
    }
    if (!$src->get_filename())
    {
        # Brand new cxbottle.conf, get MenuRoot from $productid.conf
        my $cxconfig=CXConfig->new("$cx_root/etc/$productid.conf");
        my $menu_root=$cxconfig->get("BottleDefaults","MenuRoot");
        $s->set("MenuRoot",$menu_root) if (defined $menu_root);
    }

    # Do the final merge and write the new configuration file
    $dst->merge($src);
    $dst->write($filename);

    return $old_version;
}


sub upgrade_wine_config($)
{
    my $old_version=$_[0];
    my $filename="$ENV{CX_BOTTLE}/config";
    cxlog("\n** Upgrading $filename\n\n");
    my $src=CXUpgradeConfig->new($filename);
    if (!defined $src)
    {
        print STDERR "$name0:warning: unable to read $filename: $!\n";
        $src=CXUpgradeConfig->new(undef);
    }
    else
    {
        my $backup="$filename.$old_version";
        if (!-f $backup and !copy($filename,$backup))
        {
            print STDERR "$name0:warning: unable to write backup to $backup: $!\n";
        }
    }

    my $template="$template_dir/config";
    my $dst=CXUpgradeConfig->new($template);
    if (!defined $dst)
    {
        print STDERR "$name0:error: unable to read $template: $!\n";
        return;
    }
    $dst->{quote}="\"";

    # Tweak the configuration values
    # (delete any setting which we want to pick up from the new template)
    my $s;

    # Change ${XXX} to %XXX%
    foreach my $section ($src->get_sections())
    {
        my $fields=$src->get($section)->get_fields();
        foreach my $field (values %$fields)
        {
            my $value=$field->get_value();
            next if (!defined $value);
            if ($value=~ s/\${(\w+)}/\%$1\%/g)
            {
                $field->set_value($value);
            }
        }
    }

    # Remove drive x:
    $s=$src->remove("Drive X");

    # Regenerate floppy and cdrom drives
    for (my $i=0;$i<26;$i++)
    {
        my $drive=chr(ord('A')+$i);
        $s=$src->get("Drive $drive");
        next if (!defined $s);
        my $type=$s->get("Type");
        next if (!defined $type);
        if ($type eq "floppy" or $type eq "cdrom")
        {
            $src->remove("Drive $drive");
        }
    }

    # Change the type of drives y: and z:
    foreach my $drive ("Y","Z")
    {
        $s=$src->get("Drive $drive");
        if (defined $s)
        {
            $s->remove_field("Type");
        }
    }

    # Change the Temp and Path settings
    $s=$src->get("Wine");
    if (defined $s)
    {
        $s->remove_field("Progman");
        $s->remove_field("Temp");

        my $value=$s->get("Path");
        if (defined $value)
        {
            $value =~ s/x:\\\\;//;
            $s->set("Path",$value);
        }
    }

    # Change some dll overrides
    $s=$src->get("DllOverrides");
    if (defined $s)
    {
        $s->remove_field("cabinet");
        $s->remove_field("ddraw");
        $s->remove_field("mapi");
        $s->remove_field("mapi32");
        $s->remove_field("urlmon");
    }

    # Update the x11drv section
    $s=$src->{sections}->{"x11drv"};
    if (defined $s)
    {
        $s->remove_field("TextCP");
        $s->remove_field("UseXShm");
        $s->remove_field("XVideoPort");

        foreach my $field_name ("ClientSideWithCore",
                                "ClientSideWithRender",
                                "ClientSideAntiAliasWithCore",
                                "ClientSideAntiAliasWithRender")
        {
            my $field=$s->get_field("Dont$field_name");
            if (defined $field)
            {
                my $value=$field->get_value();
                $value=(($value || "N") =~ /^N/i ? "Y" : "N");
                $s->remove_field("Dont$field_name");
                $s->set($field_name,$value) if ($value eq "N");
            }
        }
    }

    # Change some font aliases
    $s=$src->get("Fonts");
    if (defined $s)
    {
        $s->remove_field("Alias0");
        $s->remove_field("Alias1");
    }

    # Change clipboard settings
    if ($old_version lt "1.3.1")
    {
        $s=$src->get("Clipboard");
        my $entry=$s->get_entry("ClearAllSelections");
        if (defined $entry)
        {
            $s->set_entry($entry,"1");
        }

    }

    # Change the reboot setting
    $s=$src->get("Restart");
    if (defined $s)
    {
        my $entry=$s->get_entry("Boot");
        if (defined $entry)
        {
            $s->set_entry($entry,"c:\\Windows\\System\\reboot.exe");
        }
    }

    # Change the RelayExclude setting
    $s=$src->get("Debug");
    if (defined $s)
    {
        my $value=$s->get("RelayExclude");
        if (defined $value and $value eq "RtlEnterCriticalSection;RtlLeaveCriticalSection")
        {
            $s->remove_field("RelayExclude");
        }
    }

    # Remove the Console section
    $src->remove("Console");

    # Remove the [spy] and [acmsetup] sections
    if ($old_version lt "1.3.1")
    {
        $src->remove("Spy");
        $src->remove("AppDefaults\\\\acmsetup.exe\\\\x11drv");
    }

    # Add the DenyShellExecute setting
    $s=$src->get("AppDefaults\\\\OUTLOOK.EXE");
    if (!defined $s)
    {
        my $cxconfig=CXConfig->new("$cx_root/etc/$productid.conf");
        my $outlook;
        $s=$cxconfig->get("BottleDefaults");
        if ($s)
        {
            $outlook=$s->get("BlockedExtensions") if ($s->get("OutlookSecurity"));
        }
        else
        {
            # FIXME: We probably have not upgraded the CrossOver
            # configuration file yet so this field is not set... yet.
            $outlook="bat;com;exe;hta;lnk;pif;scr;vbe;vbs;wsf;wsh";
        }
        if ($outlook)
        {
            $s=$src->add("AppDefaults\\\\OUTLOOK.EXE");
            $s->set("DenyShellExecute",$outlook);

            # Do the final merge and write the new configuration file
            $dst->merge($src);
            $dst->write("$ENV{CX_BOTTLE}/config");
        }
    }

    # Remove unneeded AppDefaults sections
    $src->remove("AppDefaults\\\\QuickTimeInstaller.exe\\\\x11drv");
    $src->remove("AppDefaults\\\\QuickTimeInstaller(1).exe\\\\x11drv");
    $src->remove("AppDefaults\\\\IpxSet32.exe\\\\x11drv");

    $src->remove("AppDefaults\\\\msiexec.exe\\\\DllOverrides");
    $src->remove("AppDefaults\\\\ie6setup.exe\\\\DllOverrides");
    $src->remove("AppDefaults\\\\ie6wzd.exe\\\\DllOverrides");

    # Remove the obsolete [AppDefaults\\*\\Version] sections
    $src->remove("AppDefaults\\\\_INS5576._MP\\\\x11drv");
    if ($old_version lt "2.0.0")
    {
        foreach my $key ($src->get_sections())
        {
            next if ($key !~ /^AppDefaults\\\\.*\\\\Version$/i);
            $s=$src->get($key);
            my $value=$s->get("Windows");
            if (defined $value and $value eq "win98")
            {
                $src->remove($key);
            }
        }
    }

    # Switch to 800x600
    if ($old_version lt "2.0.0")
    {
        foreach my $key ($src->get_sections())
        {
            next if ($key !~ /^AppDefaults\\\\.*\\\\x11drv$/i);
            $s=$src->get($key);
            my $value=$s->get("Desktop");
            if (defined $value and $value eq "640x480")
            {
                $s->set("Desktop","800x600");
            }
        }
    }

    # Do the final merge and write the new configuration file
    $dst->merge($src);
    $dst->write($filename);

    # And add the drives
    system("$cx_root/bin/cxsetup","--setup");
}


sub upgrade_win_ini($)
{
    my $old_version=$_[0];
    my $filename="$ENV{CX_BOTTLE}/win.ini";
    cxlog("\n** Upgrading $filename\n\n");
    my $src=CXUpgradeConfig->new($filename);
    if (!defined $src)
    {
        print STDERR "$name0:warning: unable to read $filename: $!\n";
        $src=CXUpgradeConfig->new(undef);
    }
    else
    {
        my $backup="$filename.$old_version";
        if (!-f $backup and !copy($filename,$backup))
        {
            print STDERR "$name0:warning: unable to write backup to $backup: $!\n";
        }
    }

    my $template="$template_dir/win.ini";
    my $dst=CXUpgradeConfig->new($template);
    if (!defined $dst)
    {
        print STDERR "$name0:error: unable to read $template: $!\n";
        return;
    }

    # Tweak the configuration values
    # (delete any setting which we want to pick up from the new template)

    # Nothing to do yet except for the final merge

    # Do the final merge and write the new configuration file
    $dst->merge($src);
    $dst->write($filename);
}

sub upgrade_bottle($)
{
    my $old_version=upgrade_cxbottle($_[0]);
    upgrade_win_ini($old_version);
    upgrade_wine_config($old_version);

    # Upgrade the dotwine tree
    if (open FH,"find \"$cx_root/support/templates/dotwine/fake_windows\" -type f |")
    {
        foreach my $template (<FH>)
        {
            chomp $template;
            next if ($template =~ m%$cx_root/support/templates/dotwine/setup%);
            my $file=$template;
            $file =~ s%^$cx_root/support/templates/dotwine%$ENV{CX_BOTTLE}%;

            my $copy;
            if (-f $file)
            {
                # 'Instead of 2' is for our old rundll32.exe implementation
                $copy=!CXUtils::cxsystem("egrep \"(wine_dll_register|CodeWeavers|Wine|launchurl|Instead of 2)\" \"$file\" >/dev/null 2>&1");
            }
            else
            {
                $copy=1;
            }

            if ($copy)
            {
                CXUtils::cxsystem("cp",$template,$file);
                my $mode="u+w,a+r";
                $mode .= "x" if ($file =~ /\.exe$/);
                CXUtils::cxsystem("chmod","-R",$mode,$file);
            }
        }
        close FH;
    }
    my $file="$ENV{CX_BOTTLE}/generic.ppd";
    if (-f $file)
    {
        if (!CXUtils::cxsystem("grep \"WINE v20010509\" \"$file\" >/dev/null 2>&1"))
        {
            CXUtils::cxsystem("mv","$file","$file-$old_version");
            CXUtils::cxsystem("cp","$cx_root/support/templates/dotwine/generic.ppd","$file");
        }
    }
    else
    {
        CXUtils::cxsystem("cp","$cx_root/support/templates/dotwine/generic.ppd","$file");
    }

    my $dir="$ENV{CX_BOTTLE}/fake_windows/Windows/Icons";
    CXUtils::cxsystem("mkdir","-p",$dir);

    # Ugrade the registry
    my @reg_files;
    if ($old_version =~ /^1\.0\.0/)
    {
        CXUtils::cxsystem("$cx_root/bin/wine","--wl-app","regedit.exe","/d","HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Print\\Printers\\Wine PostScript Driver\\PrinterDriverData\\FontSubTable");
        push @reg_files,"update_1.0.0-1.1.0.reg";
    }
    if ($old_version =~ /^1\.1\.0/ or @reg_files)
    {
        push @reg_files,"update_1.1.0-1.2.0.reg";
    }
    if ($old_version =~ /^1\.2\.0/ or @reg_files)
    {
        push @reg_files,"update_1.3.0-1.3.1.reg";
    }
    if ($old_version =~ /^1\.3\.[123456]/ or @reg_files)
    {
        push @reg_files,"update_1.3.1-2.0.0.reg";
    }
    if ($old_version =~ /^2\.0\.[01]/ or @reg_files)
    {
        push @reg_files,"update_2.0.1-2.0.2.reg";
    }
    if ($old_version =~ /^2\.0\.[23]/ or @reg_files)
    {
        push @reg_files,"update_2.0.2-2.1.0.reg";
    }
    foreach $file (@reg_files)
    {
        CXUtils::cxsystem("$cx_root/bin/wine","--wl-app","regedit.exe","$cx_root/support/templates/dotwine/setup/$file");
    }

    # Upgrade the menus
    my %gui_info;
    foreach (`"$cx_root/bin/locate_gui.sh" --menu`)
    {
        chomp;
        my ($k, $v) = split /\s*=\s*/;
        $gui_info{$k} = $v;
    }
    my $debian_menu="$gui_info{debian_user_menu}/$productid";
    if (-f "$debian_menu")
    {
        my $cxbottle=CXConfig->new("$ENV{CX_BOTTLE}/cxbottle.conf");
        my $bottle_id=$cxbottle->get("Bottle","BottleID");
        if (! -f "$debian_menu-$bottle_id")
        {
            CXUtils::cxsystem("mv","$debian_menu","$debian_menu-$bottle_id");
        }
    }
}


#####
#
# Main
#
#####

# Parse the command line arguments
use CXOpts;
my $opt_create;
my $opt_upgrade;
my $opt_updater;
my $opt_old_version;
my $opt_verbose;
my $opt_help;
my $cxopts=CXOpts->new(["stop_on_non_option"]);
$cxopts->add_options(["create"        => \$opt_create,
                      "upgrade"       => \$opt_upgrade,
                      "updater=s"     => \$opt_updater,
                      "old-version=s" => \$opt_old_version,
                      "verbose!"      => \$opt_verbose,
                      "?|h|help"      => \$opt_help
                     ]);
my $err=$cxopts->parse();
$ENV{"CX_BOTTLE"}=shift @ARGV if (@ARGV);
CXLog::fdopen(2) if ($opt_verbose);


# Verify command line options
my $usage;
if ($err)
{
    print STDERR "$name0:error: $err\n";
    $usage=2;
}
elsif ($opt_help)
{
    $usage=2;
}
elsif (@ARGV)
{
    print STDERR "$name0:error: unknown option '$ARGV[0]'\n";
    $usage=2;
}
else
{
    my $cmd_count=0;
    $cmd_count++ if ($opt_create);
    $cmd_count++ if ($opt_upgrade);
    if ($cmd_count>1)
    {
        print STDERR "$name0:error: --create and --upgrade are exclusive\n";
        $usage=2;
    }
    elsif ($cmd_count==0)
    {
        if (!-d $ENV{"CX_BOTTLE"})
        {
            $opt_create=1;
        }
        else
        {
            my $mtime_ref=(stat("$template_dir/cxbottle.conf"))[9];
            my $mtime_bottle=(stat("$ENV{CX_BOTTLE}/cxbottle.conf"))[9];
            if ($mtime_ref and $mtime_bottle and $mtime_ref < $mtime_bottle)
            {
                # Already up to date
                exit 0
            }
            $opt_upgrade=1;
        }
    }
    elsif ($opt_create and -d $ENV{"CX_BOTTLE"})
    {
        print STDERR "$name0:error: this bottle already exists ($ENV{\"CX_BOTTLE\"})\n";
        $usage=1;
    }
    elsif ($opt_upgrade and !-d $ENV{"CX_BOTTLE"})
    {
        print STDERR "$name0:error: bottle directory not found ($ENV{\"CX_BOTTLE\"})\n";
        $usage=1;
    }
    $opt_old_version=~s/[^0-9.].*$// if (defined $opt_old_version);
}


# Print usage
if ($usage)
{
    print STDERR "Usage: $name0 --create [--updater update_script] [--verbose]\n";
    print STDERR "or     $name0 --upgrade [--old-version oldversion] [--verbose]\n";
    exit $usage;
}


# And finally, create/upgrade the bottle
if ($opt_create)
{
    create_bottle($opt_updater);
}
else
{
    upgrade_bottle($opt_old_version);
}

exit 0;
