# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=libssh
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.9.5
pkgrel=3
pkgdesc="Library for accessing ssh client services through C libraries (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://www.libssh.org/"
license=("LGPL")
makedepends=("${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-cmocka"
             "${MINGW_PACKAGE_PREFIX}-ninja")
depends=("${MINGW_PACKAGE_PREFIX}-openssl"
         "${MINGW_PACKAGE_PREFIX}-zlib")
options=('staticlibs' 'strip')
validpgpkeys=('8DFF53E18F2ABC8D8F3C92237EE0FC4DCC014E3D') # Andreas Schneider <asn@cryptomilk.org>
source=("https://www.libssh.org/files/${pkgver%.*}/${_realname}-${pkgver}.tar.xz"{,.asc}
        "mingw-as-unix.patch"
         001-install-static-lib.patch
         010-lld.patch)
sha256sums=('acffef2da98e761fc1fd9c4fddde0f3af60ab44c4f5af05cd1b2d60a3fa08718'
            'SKIP'
            '314a26c63de04425c6dda570a0a49c106da857c666bdf67c373dda0ddebee517'
            '10f63ebaef00097119d8e4a111874b588506339d36d3daa057e7580f62c4927e'
            'd94cbf3d951e569742185c6a2e88bbb8994f69ce32ff4e8dfb5e47149c23675a')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/mingw-as-unix.patch
  patch -p1 -i ${srcdir}/001-install-static-lib.patch
  patch -p1 -i ${srcdir}/010-lld.patch
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  [[ -d ${srcdir}/build-${MINGW_CHOST} ]] && rm -rf ${srcdir}/build-${MINGW_CHOST}
  mkdir -p ${srcdir}/build-${MINGW_CHOST} && cd ${srcdir}/build-${MINGW_CHOST}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DWITH_GSSAPI=OFF \
    -DUNIT_TESTING=ON \
    -DBUILD_STATIC_LIB=ON \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/libssh/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
