# Maintainer: George Rawlinson <grawlinson@archlinux.org>

pkgname=buf
pkgver=1.64.0
pkgrel=1
pkgdesc='A tool for working with Protocol Buffers'
arch=(x86_64 aarch64)
url='https://buf.build'
license=(Apache-2.0)
depends=(glibc)
makedepends=(git go)
source=("$pkgname::git+https://github.com/bufbuild/buf#tag=v$pkgver")
sha512sums=('873f5852163a1c063e4de54a816ea30ad19a1e257ce9b93654fc2b743bc088f09cfe10154d0d656df7a0d3ccf84a0344d17aad03aece09a54d784b735c5f63ef')
b2sums=('e135d449977ccec313bf2faaf2c35bb1001e3c9386322255f615333a0597889fc2395df34d6456227003d53b98a6ff510fd238ae8144b86439df67ffc9d61bdb')

prepare() {
  cd "$pkgname"

  # create directory for build output
  mkdir build

  # download dependencies
  export GOPATH="${srcdir}"
  go mod download
}

build() {
  cd "$pkgname"

  # set Go flags
  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export GOPATH="${srcdir}"

  go build -v \
    -buildmode=pie \
    -mod=readonly \
    -modcacherw \
    -ldflags "-compressdwarf=false \
    -linkmode external \
    -extldflags '${LDFLAGS}'" \
    -o build \
    ./cmd/...

  # generate shell completions
  for shell in bash fish zsh; do
    ./build/buf completion "$shell" > "build/completion.$shell"
  done

  # generate manpages
  mkdir -p build/manpages
  ./build/buf manpages build/manpages

  # ensure manpages are reproducible
  local _commit_date=$(git show --no-patch --format=%cd --date=format:%Y-%m-%d)
  sed \
  -e "s/^\(\.TH.* \"\)\w\{3\} [0-9]\{4\}/\1${_commit_date}/" \
  -e "s/.*\( Auto generated by spf13\/cobra\)$/${_commit_date}\1/" \
  -i build/manpages/*
}

package() {
  cd "$pkgname"

  # binaries
  install -vDm755 -t "$pkgdir/usr/bin" build/{buf,protoc-gen-buf-lint,protoc-gen-buf-breaking}

  # shell completions
  install -vDm644 build/completion.bash "$pkgdir/usr/share/bash-completion/completions/buf"
  install -vDm644 build/completion.fish "$pkgdir/usr/share/fish/vendor_completions.d/buf.fish"
  install -vDm644 build/completion.zsh "$pkgdir/usr/share/zsh/site-functions/_buf"

  # man pages
  install -vDm644 build/manpages/* -t "$pkgdir/usr/share/man/man1"
}
