# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=podman
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=5.6.2
pkgrel=1
pkgdesc='Tool for running OCI-based containers in pods (mingw-w64)'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/containers/podman"
msys2_references=(
  "anitya: 93284"
  "archlinux: podman"
  "cpe: cpe:/a:podman_project:podman"
  "gentoo: app-containers/podman"
  "purl: pkg:golang/github.com/containers/podman/v5"
)
license=('spdx:Apache-2.0')
makedepends=(
    "${MINGW_PACKAGE_PREFIX}-go"
    "${MINGW_PACKAGE_PREFIX}-cc"
    "${MINGW_PACKAGE_PREFIX}-python"
    "${MINGW_PACKAGE_PREFIX}-gettext-runtime"
    "git" "man-db"  # needed during the build
)
options=('!strip')
_GV_VERSION="v0.8.6"  # See gvisor-tap-vsock in go.mod
source=("https://github.com/containers/podman/archive/v$pkgver/${_realname}-${pkgver}.tar.gz"
        "https://github.com/containers/gvisor-tap-vsock/archive/${_GV_VERSION}/gvisor-tap-vsock-${_GV_VERSION#v}.tar.gz")
sha256sums=('c6de8f347ee93e4626d7c82e3adcb1b34e64175b5ca9959e790e52a0b4bbf2a1'
            'eb08309d452823ca7e309da2f58c031bb42bb1b1f2f0bf09ca98b299e326b215')
noextract=("${_realname}-${pkgver}.tar.gz")

prepare() {
    echo "Extracting ${_realname}-${pkgver}.tar.gz ..."
    tar -xzf ${_realname}-${pkgver}.tar.gz | true
    rm -rf build-${MSYSTEM}
    cp -r ${_realname}-${pkgver} build-${MSYSTEM}
    cp -r "gvisor-tap-vsock-${_GV_VERSION#v}" "build-proxy-${MSYSTEM}"

    cd "${srcdir}/build-${MSYSTEM}"
    _gomod_gv_version=$(go list -m -f '{{.Version}}' github.com/containers/gvisor-tap-vsock)
    if [[ "${_gomod_gv_version}" != "$_GV_VERSION" ]]; then
        echo "Error: _GV_VERSION does not match the version (${_gomod_gv_version}) in go.mod"
        exit 1
    fi
}

build() {
    export GOOS=windows
    export GOROOT=${MINGW_PREFIX}/lib/go
    export CGO_CPPFLAGS="${CPPFLAGS}"
    export CGO_CFLAGS="${CFLAGS}"
    export CGO_CXXFLAGS="${CXXFLAGS}"
    export CGO_LDFLAGS="${LDFLAGS}"
    export GO_LDFLAGS="-s -w"
    export GOFLAGS="-trimpath -modcacherw -ldflags=-linkmode=external"
    case "${CARCH}" in
      i686|x86_64)
        GOFLAGS+=" -buildmode=pie"
        ;;
    esac

    cd  "${srcdir}/build-proxy-${MSYSTEM}"
    make win-gvproxy win-sshproxy

    cd "${srcdir}/build-${MSYSTEM}"
    # parallel make breaks markdown processing
    make -j1 podman-remote CGO_ENABLED=1
    make -j1 docker-docs CGO_ENABLED=1
}

package() {
    cd "build-${MSYSTEM}"

    # copy the proxy binaries where install.remote expects them
    cp "${srcdir}/build-proxy-${MSYSTEM}/bin/"* "./bin/windows"

    # skip convert for mingw envsubst
    MSYS2_ENV_CONV_EXCL="BINDIR;ETCDIR" \
        make install.remote install.docker-full install.man install.completions DESTDIR="$pkgdir" PREFIX=${MINGW_PREFIX} ETCDIR=${MINGW_PREFIX}/etc
    rm -Rf "${pkgdir}${MINGW_PREFIX}/lib"
}
