#!/usr/bin/perl

use strict;

use Encode;
use File::Basename;
use File::Find;
use Foundation;
#use Data::Dumper;

################################################################################
# Determine running language and Country, then make an alias of the UG folder to 
# the root volume.

my $debug = 0;
my $language;
my $country;

my $GlobalPrefs = '/Library/Preferences/.GlobalPreferences.plist';
#my $GlobalPrefs = '/tmp/GlobalPreferences.plist';
my $configdict = NSDictionary->dictionaryWithContentsOfFile_($GlobalPrefs);
my $configref     = Foundation::perlRefFromObjectRef($configdict);

$language = currentRunningLanguage();
# These ifs are in because the lang prefixes on the .strings files
# for these two don't match what is returned by defaults.
if ( $language =~ /zh-Hant/ ) {
	$language = 'zh_TW';
}
elsif ( $language =~ /zh-Hans/ ) {
	$language = 'zh_CN';
}

$country = currentLocale();
#$country = 'JP'; # for testing Japan
print "Main:\n" if ( $debug );
print "$language\n" if ( $debug );
print "$country\n" if ( $debug );

removeAPCert() if ($country =~ /JP/); 

makealiases() unless ( $debug );

sub makealiases {
    my $pathToUG	= "/Library/Documentation/User Guides and Information.localized";
	my $Root 		= "/";

	loclink ( $pathToUG, $Root );
}

sub loclink {
    my $src  = shift;
    my $dest = shift;

    my $target;

    if ( $src =~ m|\/(.*?)\.localized\/?$| ) {
        my $stringsKey  = basename( $1 );
        my $stringsFile = catfile( $src, ".localized", $language . ".strings" );

        if ( -e $stringsFile ) {
            open STRINGF, "<:encoding(UTF-16)", $stringsFile;
            while (<STRINGF>) {
                if ( $_ =~ /\"(.*)\"\s+=\s+\"(.*)\"/ ) {
                    my $key = encode_utf8($1);
                    $target = encode_utf8($2);
                    $stringsKey = encode_utf8($stringsKey);
                    undef $target unless ( $key =~ /$stringsKey/i );
                }
            }
            close STRINGF;
        }
        else {
            $target = $stringsKey;
        }
    }
    else {
        $target = $src;
        $target =~ s|/$||;
        $target = basename ( $target );
    }

    my $finalDest = catfile( $dest, $target );
    print "Creating symlink from $src to $finalDest\n";
    symlink( $src, $finalDest );
    unlink "/.DS_Store" if ( -e "/.DS_Store" );

}

sub removeAPCert{ # for Japan
    # Delete Aiport Cert for JA.
    my $filePath = "/Library/Documentation/User Guides And Information.localized/";
    my $APCert = "AirPort";
    
    my %wanted = ( wanted 	=> 	sub 
        { 
 	# Handle APCert as a regex 
 	if ($_ =~ /$APCert/i) {
        #logprint("removing $_");
        $debug || unlink $_ || warn "could not unlink $_";
	}
	}
	);
        ### Find and delete APCert
	File::Find::find(\%wanted, $filePath); # Remove APCert.	
}

sub currentRunningLanguage {
    
    my @lang = ( ref $configref->{AppleLanguages} )
       	? @{ $configref->{AppleLanguages} }
        : ['en'];
    
    
	print "from cRL => $lang[0]" . "\n" if ( $debug );
	print "Language running is $lang[0]" . "\n";
	return $lang[0];

	#my @Langs = `defaults read 'Apple Global Domain' AppleLanguages`;
	#my @L = map{ /\s\"*\b(.*)\b\"*/ } @Langs;
	#print "Available Languages:\n@L\n" if ($debug);
	#print "Running Language:\n$L[0]\n" if ($debug);
	#return $L[0];
}

sub currentLocale {

	my $c = ( $configref->{Country} )
       	? $configref->{Country}
        : 'US';
        
	print "from cLocale => $c" . "\n" if ( $debug );
	print "Country is $c" . "\n";
	return $c;
	
	#my $Locale = `defaults read 'Apple Global Domain' AppleLocale`;
	#chomp $Locale;
	#my($lang, $country) = split('_', $Locale);
	#print "Locale:\n$Locale\n" if ($debug);
	#print "Lang:\n$lang\n" if ($debug);
	#print "Country:\n$country\n" if ($debug);
	
	#return $country;
}

sub catfile {
    my $result = join "/", @_;
    $result =~ s/\/+/\//g;
    return $result;
}

################################################################################
# always
exit 0;
