# Maintainer: Jeremy Drake <github@jdrake.com>
# borrowed heavily from https://github.com/mstorsjo/llvm-mingw/blob/22ef26848995f2a3ccd0f1c13a2fcff60613a54b/build-libssp.sh

_realname=libssp
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=7.3.0
pkgrel=1
pkgdesc="A library for stack smashing protection (mingw-w64)"
arch=('any')
mingw_arch=('clang32' 'clang64' 'clangarm64')
url="https://gcc.gnu.org"
license=('LGPL' 'custom')
makedepends=("${MINGW_PACKAGE_PREFIX}-clang")
source=("libssp.tar.bz2::https://gitlab.com/watched/gcc-mirror/gcc/-/archive/releases/gcc-7.3.0/gcc-releases-gcc-7.3.0.tar.bz2?path=libssp"
        "https://gitlab.com/watched/gcc-mirror/gcc/-/raw/releases/gcc-7.3.0/COPYING.RUNTIME"
        "libssp-Makefile")
noextract=("libssp.tar.bz2")
sha256sums=('f5fa12f8e0ec23fa018c9545459255cfc37fb34b7a1661cff2500dd1b116d057'
            '9d6b43ce4d8de0c878bf16b54d8e7a10d9bd42b75178153e3af6a815bdc90f74'
            '7936cef86f5128e6e66afc77cd9c815773a29842a921e95680a05ff0fdb515dd')

prepare() {
  cd "${srcdir}"
  rm -rf libssp
  tar -jxf "${srcdir}/libssp.tar.bz2" --strip-components=1
  cp -f libssp-Makefile libssp/Makefile
  cd libssp
  # gcc/libssp's configure script runs checks for flags that clang doesn't
  # implement. We actually just need to set a few HAVE defines and compile
  # the .c sources.
  cp -f config.h.in config.h
  for i in HAVE_FCNTL_H HAVE_INTTYPES_H HAVE_LIMITS_H HAVE_MALLOC_H \
    HAVE_MEMMOVE HAVE_MEMORY_H HAVE_MEMPCPY HAVE_STDINT_H HAVE_STDIO_H \
    HAVE_STDLIB_H HAVE_STRINGS_H HAVE_STRING_H HAVE_STRNCAT HAVE_STRNCPY \
    HAVE_SYS_STAT_H HAVE_SYS_TYPES_H HAVE_UNISTD_H HAVE_USABLE_VSNPRINTF \
    HAVE_HIDDEN_VISIBILITY; do
    cat config.h | sed 's/^#undef '$i'$/#define '$i' 1/' > tmp
    mv -f tmp config.h
  done
  cat ssp/ssp.h.in | sed 's/@ssp_have_usable_vsnprintf@/define/' > ssp/ssp.h
}

build() {
  [[ -d "${srcdir}/build-${CARCH}" ]] && rm -rf "${srcdir}/build-${CARCH}"
  mkdir -p "${srcdir}/build-${CARCH}" && cd "${srcdir}/build-${CARCH}"
  make -f ../libssp/Makefile
}

package() {
  cd "${srcdir}/build-${CARCH}"
  mkdir -p "${pkgdir}${MINGW_PREFIX}"/{bin,lib}
  cp -f libssp.a "${pkgdir}${MINGW_PREFIX}/lib"
  cp -f libssp_nonshared.a "${pkgdir}${MINGW_PREFIX}/lib"
  cp -f libssp.dll.a "${pkgdir}${MINGW_PREFIX}/lib"
  cp -f libssp-0.dll "${pkgdir}${MINGW_PREFIX}/bin"

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