#!/usr/bin/perl

use strict;
use Config;
use Module::Build;

my $prefix = $ENV{LIB_PREFIX} || die "No LIB_PREFIX defined, cannot build\n";

my $defines = '-DHAVE_JPEG -DHAVE_FT -DHAVE_GIF -DHAVE_PNG -DHAVE_ANIMGIF -DVERSION_33 -DHAVE_UNCLOSEDPOLY -DHAVE_FTCIRCLE';

my $MSVC = ( $^O eq 'MSWin32' && $Config{cc} =~ /\bcl(\.exe)?$/i ) ? 1 : 0;

# fontconfig isn't supported when using MSVC or on AIX due to build issues
my $use_fontconfig = ( $MSVC || $^O eq 'aix' ) ? 0 : 1;

$defines .= ' -DHAVE_FONTCONFIG' if $use_fontconfig;

if ( $^O eq 'MSWin32' ) {
    # Needed to match the way static libgd is built on Win32, and not look for a shared DLL
    $defines .= ' -D_WIN32 -DBGDWIN32 -DNONDLL';
}

# This file is needed by lib/GD/Image.pm.PLS
open my $fh, '>', '.config.cache';
print $fh $defines . "\n";
close $fh;

# Library dependency tree:
# gd
#   jpeg
#   iconv
#   fontconfig
#     expat
#     freetype
#       bz2
#       png16
#         z

my @linker_flags;
my @libs = qw(gd jpeg);
push @libs, 'fontconfig' if $use_fontconfig;
push @libs, qw(expat iconv freetype png bz2 z);

# Statically link all supporting .lib/.a files
if ( $MSVC ) {
    # MSVC, where ExtUtils::CBuilder doesn't rewrite the gcc-style ldflags
    push @linker_flags, "-libpath:$prefix/lib";
    push @linker_flags, map { 'lib' . $_ . '.lib' } @libs;
}
else {
    push @linker_flags, map { "$prefix/lib/lib" . $_ . $Config{_a} } @libs;
    push @linker_flags, "-lm";
}

my $build = Module::Build->new(
    module_name         => 'GD',
    dist_version_from   => 'lib/GD.pm',
    dist_author         => 'Lincoln Stein <lincoln.stein@gmail.com>',
    dist_abstract       => 'Perl interface to the gd2 graphics library',
    license             => 'perl',
    requires            => {
        'Math::Trig'    => 0,
    },
    build_requires      => {
        'ExtUtils::CBuilder' => 0,
    },
    configure_requires => {
        'Module::Build' => 0.42,
    },
    include_dirs        => [
        "$prefix/include",
    ],
    extra_linker_flags  => \@linker_flags,
    PL_files            => {
        'lib/GD/Image.pm.PLS' => 'lib/GD/Image.pm',
    },
    extra_compiler_flags => $defines,
    meta_merge => {
        'meta-spec' => { version => 2 },
        x_repository => {
            type => 'git',
            url  => 'git://github.com/lstein/Perl-GD.git',
            web  => 'https://github.com/lstein/Perl-GD',
        },
    }
);

$build->create_build_script;
