use strict;
use warnings;
use alienfile;
use File::Copy qw(copy);
use File::Path qw(make_path);
use File::Spec;

plugin 'PkgConfig' => (pkg_name => 'freetype2');

share {
    start_url 'https://download.savannah.gnu.org/releases/freetype/freetype-2.15.0.tar.gz';
    # FreeType 2.15.0 release announcement / official source archive.
    digest SHA256 => '9186627467a616d9a9e3e574748ac0c45fa77398e6364edef3041a8ba8d92f64';
    plugin 'Download';
    plugin 'Extract' => 'tar.gz';
    plugin 'Build::CMake';
    meta_prop->{out_of_source} = 1;
    meta_prop->{destdir} = 0;

    # Keep upstream's automatic detection of optional libraries.
    build [
        [ '%{cmake}', @{ meta->prop->{plugin_build_cmake}{args} },
          '-DCMAKE_BUILD_TYPE=Release',
          '-DCMAKE_INSTALL_LIBDIR=lib',
          '-DBUILD_SHARED_LIBS=OFF',
          '-DCMAKE_POSITION_INDEPENDENT_CODE=ON',
          '%{.install.extract}' ],
        '%{make}',
        '%{make} install',
    ];

    after build => sub {
        my ($build) = @_;
        my $prefix = $build->install_prop->{prefix};
        my $source = $build->install_prop->{extract};
        my $pc = File::Spec->catfile($prefix, 'lib', 'pkgconfig', 'freetype2.pc');

        # Preserve upstream's flags and dependency metadata; relocate the prefix.
        open my $in, '<', $pc or die "Cannot read $pc: $!";
        my $text = do { local $/; <$in> };
        close $in or die $!;
        $text =~ s/^prefix=.*$/prefix=\${pcfiledir}\/..\/../m
            or die "No prefix in $pc";
        open my $out, '>', $pc or die "Cannot write $pc: $!";
        print {$out} $text;
        close $out or die $!;

        my $licenses = File::Spec->catdir($prefix, 'share', 'licenses', 'FreeType');
        for my $name (qw(LICENSE.TXT docs/FTL.TXT docs/GPLv2.TXT
                         src/bdf/README src/pcf/README src/gzip/zlib.h
                         src/gzip/README.freetype)) {
            my @parts = split m{/}, $name;
            my $file = pop @parts;
            my $dir = File::Spec->catdir($licenses, @parts);
            make_path($dir);
            copy(File::Spec->catfile($source, @parts, $file),
                 File::Spec->catfile($dir, $file))
                or die "Cannot preserve $name: $!";
        }
    };
};

after gather => sub {
    my ($build) = @_;
    for my $key (qw(version cflags libs)) {
        die "FreeType metadata missing $key; check PKG_CONFIG_PATH throughout the build.\n"
            unless defined $build->runtime_prop->{$key}
                && $build->runtime_prop->{$key} =~ /\S/;
    }
};
