use alienfile;

plugin 'PkgConfig' => 'libpq';

share {
    plugin 'Download' => (
        url     => 'https://ftp.postgresql.org/pub/source/v18.3/',
        filter  => qr/^postgresql-[0-9.]+\.tar\.bz2$/,
        version => qr/^postgresql-([0-9.]+)\.tar\.bz2$/,
    );

    plugin 'Extract' => 'tar.bz2';

    plugin 'Build::Autoconf';

    # PostgreSQL requires GNU make; on BSDs %{make} resolves to BSD make
    my $make = ($^O =~ /bsd/i) ? 'gmake' : '%{make}';

    build [
        '%{configure} --prefix=%{.install.prefix} --without-readline --without-zlib --without-icu --without-openssl',
        "$make -C src/backend generated-headers",
        "$make -C src/common",
        "$make -C src/port",
        "$make -C src/interfaces/libpq",
        "$make -C src/interfaces/libpq install",
        'cp src/include/postgres_ext.h $DESTDIR/%{.install.prefix}/include/',
        'cp src/common/libpgcommon.a src/port/libpgport.a $DESTDIR/%{.install.prefix}/lib/',
        sub {
            # On macOS, fix the dylib install_name from an absolute path to
            # @rpath so it can work after Alien::Build DESTDIR relocation.
            my $build = shift;
            return unless $^O eq 'darwin';
            my $prefix  = $build->install_prop->{prefix};
            my $destdir = $ENV{DESTDIR} // '';
            my $lib     = "$destdir$prefix/lib";

            system('install_name_tool', '-id', '@rpath/libpq.5.dylib',
                   "$lib/libpq.5.dylib") == 0
                or die "install_name_tool failed";
        },
    ];
};
