#!/usr/bin/perl
# This script configures fontconfig
use strict;
use warnings;

use IO::File;
use POSIX qw(tmpnam);

# We use postconfig() helper subroutine so we have to include
# its definition
require '/usr/lib/localization-config/common/postconfig.pl';

# If no locale is given as argument, quit
my $lang = $ARGV[0] or die "No language given";

# The config filename
my $localconf = '/etc/fonts/local.conf';

# These are X settings -> see /usr/X11R6/lib/locale for charset names
my %lang_map = (
        #entries sorted alphabetically
        'el_GR.UTF-8' => { LOCALFONTS =>  make_alias('sans-serif', 'FreeSans')."\n"
                                         .make_alias('serif', 'FreeSerif')."\n"
                                         .make_alias('monospace', 'FreeMono')."\n",
                         },
             );

# Print the supported locale entries.
if ("supported" eq $lang) {
    for $lang (sort keys %lang_map) {
        print "$lang\n";
    }
    exit 0;
}

# check if the locale given is supported
my $conf;
if(defined($lang_map{$lang})) {
    $conf = $lang_map{$lang};
} else {
    die "Unsupported locale $lang\n";
}

# The following commands, do a search and replace in the file
# /etc/fonts/local.conf. We don't write in the original file, 
# instead we create a temporary file and we insert the values
# we want right before the end (</fontconfig>. The temporary
# file is then copied over the original. 
my $tmpfname, my $tmpf;
$tmpfname = $localconf.".new";
$tmpf = IO::File->new($tmpfname, O_RDWR|O_CREAT|O_EXCL);

open IN, "<$localconf"or die "Unable to open $localconf";    
while(<IN> )
{
    s/<\/fontconfig>$/$conf->{'LOCALFONTS'}<\/fontconfig>/;
    print $tmpf $_;
}
 
close $tmpf;
close IN;

rename($tmpfname, $localconf) || die "Cannot write $localconf: $!";

# This helper function is used to create easily an alias for a font
# It's quite basic and could probably be rewritten into something more
# advanced, but it will work for now.
sub make_alias {
    my ($alias, $family) = @_;

    my $result = '<alias><family>'.$alias.'</family>';
    $result .= '<prefer><family>'.$family.'</family></prefer></alias>';
    
    return $result;
}
