#!/usr/bin/perl -w
#
# grace font updater
#  Copyright 2010 Kenshi Muto <kmuto@debian.org>
# License: GNU General Public License Version 2
#
my $orgt1dir = "/usr/share/fonts/type1";
my $gt1dir = "/usr/share/grace/fonts/type1";
my $fontbase = "/usr/share/grace/fonts/FontDataBase";

sub recursiveLink {
    my($odir, $cdir) = @_;
    opendir(my $dh, $odir);
    my @files = readdir($dh);
    foreach (@files) {
	next if (/^\./);
	recursiveLink("$odir/$_", $cdir) if -d "$odir/$_";
	symlink("$odir/$_", "$cdir/$_") if -f "$odir/$_";
    }
    closedir($dh);
}

# cleanup (remove symlink only)
opendir(my $dh, $gt1dir) || die "Can't open $gt1dir: $!\n";
my @files = readdir($dh);
foreach (@files) {
    next if (/^\./);
    unlink "$gt1dir/$_" if -l "$gt1dir/$_";
}
closedir($dh);

# symlink from original font directory
recursiveLink($orgt1dir, $gt1dir);

# define essential Postscript font map
my(%map) = (
    "Times-Roman" => "n021003l.pfb",
    "Times-Italic" => "n021023l.pfb",
    "Times-Bold" => "n021004l.pfb",
    "Times-BoldItalic" => "n021024l.pfb",
    "Helvetica" => "n019003l.pfb",
    "Helvetica-Oblique" => "n019023l.pfb",
    "Helvetica-Bold" => "n019004l.pfb",
    "Helvetica-BoldOblique" => "n019024l.pfb",
    "Courier" => "n022003l.pfb",
    "Courier-Oblique" => "n022023l.pfb",
    "Courier-Bold" => "n022004l.pfb",
    "Courier-BoldOblique" => "n022024l.pfb",
    "Symbol" => "s050000l.pfb",
    "ZapfDingbats" => "d050000l.pfb",
);

# scan font files
chdir("$gt1dir");
open(my $ph, "fc-scan -f '%{fontformat}\t%{family}-%{style}\t%{file}\n' . |") || die "Can't execute fc-scan: $!\n";
while (<$ph>) {
    chomp;
    my($fontformat, $familystyle, $file) = split(/\t/);
    next if $fontformat ne "Type 1";
    $familystyle =~ s/ //g;
    $file =~ s/^\.\///;
    $map{$familystyle} = $file;
}
close($ph);

# dump FontDatabase
open(my $fh, ">$fontbase") || die "Can't create $fontbase: $!\n";
print $fh (scalar(keys %map));
print $fh "\n";
foreach (sort keys %map) {
    print $fh "$_ $_ " . $map{$_} . "\n";
}
close($fontbase);
