--- /tmp/fontconfig.defoma.orig	2007-01-15 03:43:05.000000000 +1100
+++ /tmp/fontconfig.defoma	2007-01-21 22:48:42.000000000 +1100
@@ -12,11 +12,41 @@
 use Debian::Defoma::Id;
 use Debian::Defoma::Subst;

+use File::Spec;
+use File::Basename qw(dirname);
+
 use strict;
 use warnings;

 my $PkgDir = "$ROOTDIR/fontconfig.d";
 my ($Id, $Sb);
+my @fontconfig_dirs;
+my %fccache_dirs;
+
+sub fontconfig_dirs {
+  local $_;
+  my @dirs;
+
+  foreach my $file (@_) {
+    open my $f, '<', $file or next;
+    # fontconfig files are so complicated to parse ;)
+    while (<$f>) {
+      push @dirs, m,<dir(?: [^>]*)?>(.*?)</dir>,g;
+
+      my @inc = m,<include(?: [^>]*)?>(.*?)</include>,g;
+      foreach (@inc) {
+	my $dir = File::Spec->rel2abs($_, dirname($file));
+	my $d;
+	opendir $d, $dir or next;
+	my @contents = map "$dir/$_", grep !/^\.\.?$/, readdir $d;
+	closedir $d;
+	push @dirs, fontconfig_dirs(@contents);
+      }
+    }
+  }
+
+  return @dirs;
+}

 sub init {
   $Id ||= defoma_id_open_cache() or return 1;
@@ -24,6 +54,9 @@
 			    threshold => 70,
 			    idobject => $Id) or return 1;

+  @fontconfig_dirs = fontconfig_dirs('/etc/fonts/fonts.conf')
+    unless @fontconfig_dirs;
+
   return 0;
 }

@@ -64,6 +97,16 @@
   my $font = shift;
   my $id = shift;

+  foreach my $dir (@fontconfig_dirs) {
+    if (substr($font, 0, length($dir)) eq $dir) {
+      # No need to symlink if font is already in a dir covered by
+      # fontconfig.  Still need to ensure fc-cache gets rerun on this
+      # directory however..
+      $fccache_dirs{dirname $font} = 1;
+      return 0;
+    }
+  }
+
   my $dir = $PkgDir . '/' . substr($id, 0, 1);
   my $ext = $font =~ m|\.([^/.]+)$| ? ".$1" : '';
   my $file = $id . $ext;
@@ -111,7 +154,7 @@
 EOF
   }

-  # substituded fonts
+  # substituted fonts
   foreach (defoma_id_get_font($Id, installed => type => 'SSI')) {
     print $fh <<EOF
    <alias>
@@ -128,8 +171,12 @@
   defoma_subst_close($Sb);
   defoma_id_close_cache($Id);

-  system('fc-cache', $PkgDir);
+  # need to --force, since the mtime on $PkgDir may not have changed,
+  # even though the font file at the far end of a symlink might have.
+  system('fc-cache', '--force', $PkgDir);
+  system('fc-cache', keys(%fccache_dirs)) if %fccache_dirs;

+  undef $Id;
   return 0;
 }

