# Maintainer: Amphaal <guillaume.vara@gmail.com>
# Contributor: Alexey Pavlov <alexpux@gmail.com>
# Contributor: AlexWMF <alexxwmf@gmail.com>
# Contributor: Zach Bacon <11doctorwhocanada@gmail.com>

_realname=libtorrent-rasterbar
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.11
pkgrel=2
pkgdesc="libtorrent is a feature complete C++ bittorrent implementation focusing on efficiency and scalability (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
license=('spdx:BSD-3-Clause')
url="https://libtorrent.org/"
msys2_references=(
  "cpe: cpe:/a:rasterbar_software:libtorrent"
)
depends=("${MINGW_PACKAGE_PREFIX}-boost"
         "${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkgconf")
source=("https://github.com/arvidn/libtorrent/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('f0db58580f4f29ade6cc40fa4ba80e2c9a70c90265cd77332d3cdec37ecf1e6d')

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

  mkdir "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${extra_config} \
    -DBUILD_SHARED_LIBS=ON \
    -Dbuild_tests=OFF \
    -Dbuild_examples=OFF \
    -Dbuild_tools=OFF \
    ../${_realname}-${pkgver}

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

  mkdir "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${extra_config} \
    -DBUILD_SHARED_LIBS=OFF \
    -Dbuild_tests=OFF \
    -Dbuild_examples=OFF \
    -Dbuild_tools=OFF \
    ../${_realname}-${pkgver}

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

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

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYING" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  # Remove full path reference in cmake and pkgconfig files
  local _PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  sed -s "s|${_PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libtorrent-rasterbar.pc"
  sed -s "s|${_PREFIX_WIN}/include||g" -i "${pkgdir}${MINGW_PREFIX}/lib/cmake/LibtorrentRasterbar/LibtorrentRasterbarTargets.cmake"
}
