#!/usr/bin/perl

BEGIN { die "Do not run this as root" unless $>; }

use strict;
use warnings;
use Path::Tiny;
use Text::Amuse::Compile::Fonts;
use Try::Tiny;

=pod

=head1 NAME

amusewiki-populate-webfonts - amusewiki helper for EPUB font embedding


=head1 SYNOPSIS

 amusewiki-populate-webfonts

Create the configuration file with font definitions.

It calls C<muse-create-font-file.pl fontspec.json> if the spec file is
missing and checks the existing one.

=cut

my @files = (path('fontspec.json'));
if ( -d 'repo') {
    push @files, map { path($_, qw/site_files fontspec.json/) } path('repo')->children;
}

foreach my $file (@files) {
    if ($file->exists) {
        print "Checking $file\n";
        try {
            Text::Amuse::Compile::Fonts->new("$file")->all_fonts;
        } catch {
            my $err = $_;
            my $move_to = $file . '~' . time() . '~';
            print "$file looks bad: $err\nMoving it out of the way and renaming it to $move_to\n";
            $file->move($move_to);
        };
    }
}

unless (-f 'fontspec.json') {
    my $masterfile = '/etc/amusewiki.d/fontspec.json';
    my $symlink = 0;
    if (-f $masterfile) {
        try {
            Text::Amuse::Compile::Fonts->new("$masterfile")->all_fonts;
            $symlink = 1;
        } catch {
            print "$masterfile looks invalid!";
        };
    }
    if ($symlink) {
        print "Found system wide fontspec.json, symlinking\n";
        symlink($masterfile, 'fontspec.json');
    }
    else {
        print "Generating fontspec.json\n";
        system(qw/muse-create-font-file.pl fontspec.json/) == 0 or die $!;
    }
}


