#!/usr/bin/perl -w

my $output_unix = 1;

sub reg_get_value($)
{
    # it is believed that the registry moves keys around
    # depending on OS version, this will de-mangle that
    my $key = shift;
    my $fhandle;
    my $value;

    open ($fhandle, "/proc/registry/$key") || return;
    $value = <$fhandle>;
    close ($fhandle);

    return $value;
}

sub print_syntax()
{
    print "oowintool [option] ...\n";
    print " encoding options\n";  
    print "   -w   - windows form\n";
    print "   -u   - unix form (default)\n";
    print " commands:\n";
    print "   --msvc-ver              - dump version of MSVC eg. 6.0\n";
    print "   --msvc-copy-dlls <dest> - copy msvc[pr]??.dlls into <dest>/msvcp??/\n";
    print "   --msvc-productdir       - dump productdir\n";
    print "   --psdk-home             - dump psdk install dir\n";
    print "   --help                  - this message\n";
}

sub print_path($$)
{
    my ($path, $unix) = @_;

    # 'Unterminated quoted string errors' from 'ash' when 
    # forking cygpath  so - reimplement cygpath in perl [ gack ]
    if ($output_unix && !$unix) {
	$path =~ s|\\|/|g;
	$path =~ s|([a-zA-Z]):/|/cygdrive/$1/|g;
    }
    elsif (!$output_unix && $unix) {
	$path =~ s|/cygdrive/([a-zA-Z])/|/$1/|g;
	$path =~ s|/|\\|g;
    }

    print $path;
}

sub print_psdk_home()
{
    my $value;
    $value = reg_get_value ('HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/MicrosoftSDK/Directories/Install Dir');
    defined $value || die "psdk not found";
    print_path ($value, 0);
}

if (!@ARGV) {
    print_syntax();
    exit 1;
}

my @commands = ();
while (@ARGV) {
    my $opt = shift @ARGV;
    
    if (0) {
    } elsif ($opt eq '-w') {
	$output_unix = 0;
    } elsif ($opt eq '-u') {
	$output_unix = 1;
    } else {
	push @commands, $opt;
    }
}

while (@commands) {
    my $opt = shift @commands;

    if (0) {
    } elsif ($opt eq '-w') {
	$output_unix = 0;
    } elsif ($opt eq '-u') {
	$output_unix = 1;
    } elsif ($opt eq '--msvc-ver') {
	print "Unimplemented\n";
    } elsif ($opt eq '--msvc-copy-dlls') {
	print "Unimplemented\n";
    } elsif ($opt eq '--msvc-productdir') {
	print "Unimplemented\n";
    } elsif ($opt eq '--psdk-home') {
	print_psdk_home();
    } elsif ($opt eq '--help' || $opt eq '/?') {
	print_syntax();
    } else {
	print "Unknown option '$opt'\n";
	print_syntax();
	exit 1;
    }
}

