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;

    # Only an explicit opt-in may bypass SDL's Unix desktop requirement.
    my $headless = ($ENV{ALIEN_SDL3_NATIVE_HEADLESS} // '') eq '1';

    build [
        sub {
            my ($build) = @_;
            # SDL 3.4.20 treats absent optional X11 extensions as fatal.
            # Use SDL's own header/library checks; do not duplicate them
            # with pkg-config probes that may disagree with CMake.
            my $path = File::Spec->catfile($build->install_prop->{extract},
                                          'cmake', 'sdlchecks.cmake');
            open my $in, '<', $path or die "Cannot read $path: $!";
            my $text = do { local $/; <$in> };
            close $in or die $!;
            my $count = $text =~ s{SDL_missing_dependency\((XCURSOR|XDBE|XINPUT|XFIXES|XSYNC|XRANDR|XSCRNSAVER|XSHAPE|XTEST) (SDL_X11_\1)\)}{message(STATUS "Alien::SDL3::Native: optional $1 unavailable; disabling $2")\n          set($2 OFF)}g;
            die "Unexpected SDL 3.4.20 optional X11 checks in $path (expected 9, found $count)\n"
                unless $count == 9;
            open my $out, '>', $path or die "Cannot write $path: $!";
            print {$out} $text or die $!;
            close $out or die $!;
        },
        [ '%{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',
          '-DSDL_UNIX_CONSOLE_BUILD=' . ($headless ? 'ON' : 'OFF'),
          '%{.install.extract}', sub {
              my ($build, $result) = @_;
              print STDOUT $result->{out};
              print STDERR $result->{err};
              if ($result->{exit}) {
                  if ($result->{err} =~ /SDL could not find X11 or Wayland/) {
                      die "Alien::SDL3::Native requires X11 or Wayland development libraries for desktop builds.\n"
                        . "Debian/Ubuntu: install libx11-dev libxext-dev libgl-dev.\n"
                        . "Fedora: install libX11-devel libXext-devel mesa-libGL-devel.\n"
                        . "Other platforms: https://wiki.libsdl.org/SDL3/README-linux#build-dependencies\n"
                        . "For a deliberately non-desktop build, set ALIEN_SDL3_NATIVE_HEADLESS=1.\n";
                  }
                  die "SDL3 CMake configuration failed (status $result->{exit}); see output above.\n";
              }
          } ],
        '%{make}',
        '%{make} install',
        sub {
            my ($build) = @_;
            $build->runtime_prop->{sdl3_native_headless_allowed} = $headless ? 1 : 0;
            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;
    # The environment flag also permits testing an intentionally headless
    # system SDL, but it never changes system discovery or its features.
    if ($build->is_system_install) {
        $prop->{sdl3_native_headless_allowed} =
            ($ENV{ALIEN_SDL3_NATIVE_HEADLESS} // '') eq '1' ? 1 : 0;
    }
    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};
};
