use alienfile;
use Config;
use Path::Tiny;

# Prefer the system libssh if pkg-config can find it.
# Falls back to building from the bundled source tarball.
#
# PkgConfig does probe and gather in one, for both paths: against the system
# library on the sys path, and against the libssh.pc the share build installs
# into the prefix on the share path. The hand-rolled `probe` plus a `sys`-only
# gather covered just the first of those, so a share install finished with no
# cflags, no libs and no version -- Alien::libssh->cflags came back empty and
# anything compiling against it could not find libssh/libssh.h.

# Strawberry Perl keeps zlib and OpenSSL in its toolchain tree (c\include,
# c\lib). The cmake Alien::cmake3 builds searches only Program Files and its
# own share dir there, so before Strawberry shipped a cmake of its own (5.40)
# the configure stopped at "Could NOT find ZLIB". perl's library path names
# the toolchain: each entry's parent that has an include dir is a prefix.
my %seen;
my @toolchain = $^O eq 'MSWin32'
  ? grep { -d "$_/include" && !$seen{$_}++ }
    map { path($_)->parent->stringify } split ' ', $Config{libpth}
  : ();

# The bundled libssh 0.12 builds only against OpenSSL 1.1.1 or newer. On a
# system with an older one (Debian 8, Strawberry Perl up to 5.28) cmake stopped
# the share build midway with "Found unsuitable version", and a smoker filed
# UNKNOWN. A share install checks the OpenSSL headers the compiler sees first
# and reports the system unsupported, which CPAN Testers grade NA. When the
# compiler sees no OpenSSL headers at all, cmake keeps the say.
my $openssl_before_111 = sub {
  require Capture::Tiny;
  require ExtUtils::CBuilder;
  my $dir = Path::Tiny->tempdir;
  my $cb  = ExtUtils::CBuilder->new( quiet => 1 );
  # After the system dirs, so CPATH and the compiler's own view come first.
  my @include = $Config{gccversion} ? map { ( '-idirafter', "$_/include" ) } @toolchain : ();
  my $compiles = sub {
    my ($check) = @_;
    my $src = $dir->child('openssl.c');
    $src->spew("#include <openssl/opensslv.h>\n${check}int alien_libssh_openssl_check;\n");
    my $ok;
    Capture::Tiny::capture_merged( sub {
      $ok = eval { $cb->compile( source => "$src", extra_compiler_flags => \@include ); 1 };
    } );
    return $ok;
  };
  return 0 unless $compiles->('');
  return !$compiles->("#if OPENSSL_VERSION_NUMBER < 0x10101000L\n#error OpenSSL before 1.1.1\n#endif\n");
};
my $unsupported_without_openssl_111 = sub {
  return unless $openssl_before_111->();
  print "OS unsupported: the bundled libssh needs OpenSSL 1.1.1 or newer,"
    . " and the OpenSSL headers on this system are older\n";
  exit 0;
};

# Author release only: force the bundled share build so the shipped offline
# fallback is exercised on every `dzil release` (TestRelease), even on a host
# that has a system libssh. RELEASE_TESTING marks the author release;
# !AUTOMATED_TESTING excludes thorough CPAN smokers, which set BOTH flags --
# they must keep probing for their own system libssh, not build share.
#
# This is the `override` hook (what ALIEN_INSTALL_TYPE drives), NOT a `probe`
# hook, on purpose: Alien::Build runs override before the probe hooks and lets
# 'share' win outright, whereas a probe returning 'share' only defers to the
# next probe -- PkgConfig would then still pick a present system lib, and the
# fallback would go untested at release. Registering override replaces
# Core::Override's default, so ALIEN_INSTALL_TYPE is re-checked here first to
# keep the forced-path runs (share/system) and any user override working.
#
# A forced share install skips the probe hooks, so it runs the OpenSSL check
# here.
meta->register_hook( override => sub {
  my $type = $ENV{ALIEN_INSTALL_TYPE}
    || ( $ENV{RELEASE_TESTING} && !$ENV{AUTOMATED_TESTING} ? 'share' : '' );
  $unsupported_without_openssl_111->() if $type eq 'share';
  return $type;
});

# 0.9.0 is where ssh_session_is_known_server and ssh_session_update_known_hosts
# appear, the known-hosts API Net::LibSSH calls. Without a floor any libssh
# the probe finds was accepted, and the consumer then failed at link time.
# The floor is the probe's only: the share path builds a known version.
plugin 'PkgConfig' => (
  pkg_name        => 'libssh',
  minimum_version => '0.9.0',
);

# Reached only when pkg-config found no usable system libssh: the install is
# a share install, which needs OpenSSL 1.1.1.
probe sub {
  $unsupported_without_openssl_111->();
  return 'share';
};

share {
  start_url 'file://' . Path::Tiny->cwd->child('share/libssh-0.12.2.tar.xz')->stringify;

  # start_url alone does nothing: without a fetch hook Alien::Build reaches the
  # download phase with no way to act on it and dies with "No hooks registered
  # for fetch", so the advertised fallback never existed on a box without a
  # system libssh.
  plugin 'Fetch::Local';
  plugin 'Extract' => 'tar.xz';
  plugin 'Build::CMake';

  # libssh refuses to configure in its own source tree
  # (cmake/Modules/MacroEnsureOutOfSourceBuild.cmake compares CMAKE_SOURCE_DIR
  # against CMAKE_BINARY_DIR). Build::CMake builds in the extracted directory
  # itself unless told otherwise, which is why the source path used to be '..'
  # -- a directory nothing ever created or changed into.
  meta->prop->{out_of_source} = 1;

  # One command. A flat list is a sequence of separate commands to
  # Alien::Build, so the arguments were each exec'd as a program of their own;
  # and the make steps were absent, leaving a configure that built nothing.
  # plugin_build_cmake.args carries the generator, PIC, install prefix and
  # libdir, so only the libssh-specific switches are spelled out here.
  build [
    [ '%{cmake}',
      @{ meta->prop->{plugin_build_cmake}->{args} },
      '-DCMAKE_BUILD_TYPE=Release',
      # Static, because a share install puts libssh.so where the runtime
      # linker does not look: the XS test compiled fine against the prefix and
      # then died on `libssh.so.4: cannot open shared object file`, which is
      # exactly what Net::LibSSH (also XS) would do at use time.
      '-DBUILD_SHARED_LIBS=OFF',
      '-DWITH_EXAMPLES=OFF',
      '-DWITH_PCAP=OFF',
      '-DWITH_GSSAPI=OFF',
      # The Strawberry toolchain tree, see @toolchain at the top.
      ( @toolchain ? '-DCMAKE_PREFIX_PATH=' . join( ';', @toolchain ) : () ),
      '%{.install.extract}',
    ],
    '%{make}',
    '%{make} install',
  ];

  # libssh generates its libssh.pc with a bare `Libs: -L${libdir} -lssh` and no
  # Libs.private, so a static build hands the consumer a link line that omits
  # everything libssh itself pulls in: linking with just -lssh compiles and then
  # dies on `undefined symbol: EVP_PKEY_CTX_new`. libssh is built against
  # OpenSSL here (WITH_GCRYPT and WITH_MBEDTLS both default off) and with zlib
  # (WITH_ZLIB defaults on), so those are the two to declare. This hooks after
  # gather rather than being a plain gather, because PkgConfig registers its
  # own and would otherwise run last and put the bare .pc line back.
  #
  # The library is static, which libssh.h has to be told: on Windows and Cygwin
  # it declares the API dllimport unless LIBSSH_STATIC is defined, and the
  # __imp_ssh_* symbols that asks for come only from a DLL's import library.
  # libssh's CMake sets LIBSSH_STATIC on the static target, but the .pc file
  # does not carry it. Elsewhere libssh.h does not look at it.
  #
  # libssh calls pthread_create (proxy jumps in socket.c), which lives outside
  # libc on FreeBSD, OpenBSD and glibc before 2.34, so the libs name the thread
  # library everywhere; where libc has the threads, -lpthread adds nothing. XS modules got
  # away without it because perl itself links the thread library there, a
  # stand-alone program did not. On Windows libssh's CMake links the MinGW
  # threads as well (Strawberry's gcc has the posix thread model), plus
  # iphlpapi and ws2_32, with ws2_32 last.
  after 'gather' => sub {
    my ($build) = @_;
    my @windows = $^O eq 'MSWin32' ? ( '-liphlpapi', '-lws2_32' ) : ();
    for my $key (qw( libs libs_static )) {
      my $v = defined $build->runtime_prop->{$key} ? $build->runtime_prop->{$key} : '';
      next if $v =~ /-lcrypto\b/;
      $build->runtime_prop->{$key} = join ' ', grep { length } $v, '-lcrypto', '-lz', '-lpthread', @windows;
    }
    for my $key (qw( cflags cflags_static )) {
      my $v = defined $build->runtime_prop->{$key} ? $build->runtime_prop->{$key} : '';
      next if $v =~ /-DLIBSSH_STATIC\b/;
      $build->runtime_prop->{$key} = join ' ', grep { length } $v, '-DLIBSSH_STATIC';
    }
  };
};
