use strict;
use warnings;
use alienfile;
use File::Spec;

# SDL 3.2 is the first stable SDL3 API series.
plugin 'PkgConfig' => (pkg_name => 'sdl3', atleast_version => '3.2.0');

share {
    start_url 'https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz';
    digest SHA256 => 'f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f';
    plugin 'Download';
    plugin 'Extract' => 'tar.gz';
    plugin 'Build::CMake';
    meta_prop->{out_of_source} = 1;
    meta_prop->{destdir} = 0;

    build [
        [ '%{cmake}', @{ meta->prop->{plugin_build_cmake}{args} },
          '-DCMAKE_BUILD_TYPE=Release',
          '-DCMAKE_INSTALL_LIBDIR=lib',
          '-DCMAKE_POSITION_INDEPENDENT_CODE=ON',
          '-DSDL_SHARED=OFF',
          '-DSDL_STATIC=ON',
          '-DSDL_INSTALL=ON',
          '-DSDL_INSTALL_CPACK=OFF',
          '-DSDL_TEST_LIBRARY=OFF',
          '-DSDL_TESTS=OFF',
          '-DSDL_EXAMPLES=OFF',
          '%{.install.extract}' ],
        '%{make}',
        '%{make} install',
    ];

    after build => sub {
        my ($build) = @_;
        my $prefix = $build->install_prop->{prefix};
        my $pc = File::Spec->catfile($prefix, 'lib', 'pkgconfig', 'sdl3.pc');
        if ($^O eq 'freebsd') {
            $pc = File::Spec->catfile($prefix, 'libdata', 'pkgconfig', 'sdl3.pc');
        }
        open my $in, '<', $pc or die "Cannot read $pc: $!";
        my $text = do { local $/; <$in> };
        close $in or die $!;
        # Preserve upstream dependency metadata but make the native prefix
        # relocatable when Alien::Build moves it into its final share directory.
        $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 $!;

        for my $header (qw(SDL.h SDL_version.h SDL_video.h SDL_opengl.h)) {
            my $path = File::Spec->catfile($prefix, 'include', 'SDL3', $header);
            die "Missing SDL3 development header: $path" unless -f $path;
        }
    };

    # A bundled SDL is static: ordinary downstream libs() calls must
    # include the transitive dependencies as well.
    after gather => sub {
        my ($build) = @_;
        my $prop = $build->runtime_prop;
        die "Missing static SDL3 metadata" unless $prop->{libs_static};
        $prop->{libs} = $prop->{libs_static};
        $prop->{cflags} = $prop->{cflags_static} if defined $prop->{cflags_static};
    };
};

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