#!/usr/bin/perl

use FileHandle;
use File::Basename;
use File::Temp qw/ tempfile /;
use Getopt::Long;
use POSIX;
use strict;

our $MAPDIR = '/etc/texmf/vfontmap.d';
our $VFONTMAP = '/var/lib/texmf/vfontmap';
our $VERBOSE;
our $DEBUG;
&GetOptions( 'mapdir=s' => \$MAPDIR,
	     'output=s' => \$VFONTMAP,
	     'verbose!' => \$VERBOSE,
	     'debug!'   => \$DEBUG );

&main();
exit 0;

sub main {
    if( $VERBOSE ){
	if( -f $VFONTMAP ){
	    print STDERR "Regenerating $VFONTMAP... ";
	} else {
	    print STDERR "Generating $VFONTMAP... ";
	}
    }

    my( $tmpfh, $tmpname ) = &tempfile( "vfontmapXXXXXX", DIR => &dirname( $VFONTMAP ), UNLINK => 0 );
    print $tmpfh <<"__header__";
##################################################################
#
# Please do not edit this file directly.
# If you want to change or add anything please take a look at the
# files in $MAPDIR, and invoke `update-vfontmap'.
#
###

__header__
    for my $file ( sort glob( "$MAPDIR/*.map" ) ){
	printf $tmpfh "### From file: %s\n", $file;
	open( my $fh, '<', $file ) or next;
	while( my $str = <$fh> ){
	    $str =~ s/\@([^\@]+)\@/&replace($1)/ge;
	    print $tmpfh $str;
	}
	printf $tmpfh "### End of file: %s\n", $file;
    }
    close $tmpfh;
    chmod 0644, $tmpname;
    rename $tmpname, $VFONTMAP;

    print STDERR "done\n" if $VERBOSE;
}

sub replace {
    my( $pattern ) = @_;
    my $orig = $pattern;
    if( $pattern =~ m/\A(?:Mincho\s+Roman|Mincho|Roman)(?:\|(?:Mincho\s+Roman|Mincho|Roman))*\Z/ ){
	$pattern = 'serif';
    } elsif( $pattern =~ m/\A(?:Gothic\s+SansSerif|Gothic|SansSerif)(?:\|(?:Gothic\s+SansSerif|Gothic|SansSerif)*)\Z/ ){
	$pattern = 'sansserif';
    }
    unless( $pattern =~ m/fontformat=/ ){
	$pattern .= ':fontformat=truetype';
    }
    unless( $pattern =~ m/lang=/ ){
	$pattern .= ':lang=ja';
    }
    die "Unsafe $pattern\n" if $pattern =~ m/[^-a-zA-z0-9=:]/;
    open( my $fh, "fc-match -v $pattern|" ) or die;
    while( <$fh> ){
	if( m/file:\s+"([^"]+)"/ ){
	    close $fh;
	    print STDERR "Pattern conversion: $orig => $pattern => $1\n" if $DEBUG;
	    return $1;
	}
    }
    print STDERR "Pattern conversion: $orig => $pattern => MISSING\n" if $DEBUG;
    '_WARNING_MISSING_FONT_FILE_';
}
