# Maintainer (arch): Levente Polyak <anthraxx[at]archlinux[dot]org>
# Maintainer (arch): Morten Linderud <foxboron@archlinux.org>
# Maintainer (archarm): Kevin Mihelich <kevin@archlinuxarm.org>
# Contributor: André Silva <emulatorman@hyperbola.info>
# Contributor: Márcio Silva <coadde@hyperbola.info>
# Maintainer: Luke Shumaker <lukeshu@parabola.nu>
# Contributor: Omar Vega Ramos <ovruni@gnu.org.pe>
# Contributor: Nicolás Reynolds <fauno@kiwwwi.com.ar>
# Contributor: Daniel Milewski <niitotantei@riseup.net>
# Contributor: bill-auger <bill-auger@programmer.net>


# parabola changes and rationale:
#  - adapt config files to support multiple arches
#  - allow pacstrap to create cross-arch chroots
#  - disable tests requiring networking
#  - redmine: #3372 - arch: FS#76440
#    require openssl=1.1 during openssl v3 migration
#    also openssl=1.0 for neglected/legacy systems
#    TODO: relax after some grace period (~2024)
#          2022-12-18: arch already dropped openssl-1.0
#          it is now in libre - we could maybe drop it after the grace period

# archlinuxarm changes and rationale:
#  - arch/host/flags for armv7h, and aarch64
#  - pacman.conf: architecture=armv7h/aarch64, added our aur and alarm repos
#  - makepkg.conf: adjusted C/CXX/LDFLAGS
#  - patch to sync filesystem after install/remove
#  - reverts to allow scriplet input on stdin
#  - patch to fix application/gzip change in file 5.37


pkgname=pacman
pkgver=6.1.0
pkgrel=3
pkgrel+=.parabola2
pkgdesc="A library-based package manager with dependency support"
arch=('x86_64')
arch+=('armv7h' 'i686')
url="https://www.archlinux.org/pacman/"
#license=('GPL-2.0-or-later') # TODO:
license=('GPL')
depends=('bash' 'glibc' 'libarchive' 'curl' 'gpgme' 'pacman-mirrorlist'
         'gettext' 'gawk' 'coreutils' 'gnupg' 'grep')
_upstream_keyring=$(case ${CARCH} in armv7h) echo 'archlinuxarm-keyring' ;;     \
                                     i686  ) echo 'archlinux32-keyring'  ;; esac)
depends+=('archlinux-keyring' 'parabola-keyring' ${_upstream_keyring})
depends+=('openssl>=3' 'openssl-1.0' 'openssl-1.1') # BR #3372 ease migration to openssl v3
makedepends=('meson' 'asciidoc' 'doxygen')
checkdepends=('python' 'fakechroot')
optdepends=('perl-locale-gettext: translation support in makepkg-template')
provides=('libalpm.so')
backup=(etc/pacman.conf
        etc/makepkg.conf)
options=('strip')
options+=('debug')
validpgpkeys=('6645B0A8C7005E78DB1D7864F99FFE0FEAE999BD'  # Allan McRae <allan@archlinux.org>
              'B8151B117037781095514CA7BBDFFC92306B1121') # Andrew Gregory (pacman) <andrew@archlinux.org>
source=(https://gitlab.archlinux.org/pacman/pacman/-/releases/v$pkgver/downloads/pacman-$pkgver.tar.xz{,.sig}
        revertme-makepkg-remove-libdepends-and-libprovides.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/354a300cd26bb1c7e6551473596be5ecced921de.patch
        "$pkgname-fix-msg-unknown-key.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/6bb95c8856437513ee0ab19226bc090d6fd0fb06.patch"
        "$pkgname-man-gitlab.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/95f148c2222db608a0d72d5c5577d0c71e7fa199.patch"
        "$pkgname-make-aligned-titles.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/5e0496260b7d3f9c9fcf2b1c4899e4dbcc20ff03.patch"
        "$pkgname-repo-add-parseopts.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/0571ee82bff0edbd5ffac2228d4e6ac510b9008e.patch"
        "$pkgname-drop-result-warn.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/111eed0251238a9d3f90e76d62f2ac01aeccce48.patch"
        "$pkgname-fix-debugedit.patch::https://gitlab.archlinux.org/pacman/pacman/-/commit/bae9594ac1806ce30f2af1de27c49bb101a00d44.patch"
        pacman.conf
        makepkg.conf)
source=( ${source[*]/pacman.conf/$(printf "pacman.conf.%s\n" ${arch[*]} | sort)} ) # pacman.conf.{armv7h,i686,x86_64}
source=( ${source[*]/makepkg.conf/makepkg.conf.in}                               ) # makepkg.conf.in
source+=(dummy.conf
         9001-makepkg-Treat-pkgrel-more-similarly-to-pkgver.patch
         9002-pacman-key-updatedb.patch)
source+=(1001-arch-MR152.patch) # parabola BR #3625
source_armv7h=(0001-Sychronize-filesystem.patch
               0002-Revert-close-stdin-before-running-install-scripts.patch
               0003-Revert-alpm_run_chroot-always-connect-parent2child-p.patch)
sha256sums=('5a60ac6e6bf995ba6140c7d038c34448df1f3daa4ae7141d2cad88eeb5f1f9d9'
            'SKIP'
            'b3bce9d662e189e8e49013b818f255d08494a57e13fc264625f852f087d3def2'
            '94c987046c2ff232fa0d395cddc11644840d767806711e04ef34f876a9baf217'
            '0774d7035e34661f74b673d4b0a94be877bdc0158a555b873ec6bd4e2c936377'
            '7bb64910265ce2590f593cdfd302076e49f67a68f8cc792a9aaac572d36fc842'
            '2bbfe40539513ff5775aaf900644c8985ef618f5df9af856b9d571e2501365b0'
            '160515b741aadc876a67f213029f5f62a51ff072ea4aaeb687bbe614035bf72f'
            '1f4e4cc54332e60c9da2bdabf9a80dc11db466535f1a0be298cbf654f0723721'
            # pacman.conf over-ridden
            # makepkg.conf over-ridden
)
sha256sums+=('82a696bc3254b3fa2ab2666d239445e1a431b5e7d0152690f4265b82112cc86f'  # pacman.conf.armv7h
             '8be3b33a28c74630b74d1997795424a1c0af82c26625a428ec139480fb1115a1'  # pacman.conf.i686
             '5be276a68f7ec1d0497e26afba205a9feb14308b6fddc6cae3b32a0b6e9f9bbf'  # pacman.conf.x86_64
             'd8d68a71904d3e8015bf4454e1f2ae083c7b70624c5bb4b04331ee450d4285eb') # makepkg.conf.in
sha256sums+=('8fca32bf5ee85b67c93983d7e1c93734de5e715b3bb732f7e48b88da7844f94b'  # dummy.conf
             '9ccc7ef5bd27a68d8788f10c6e5b36495c5d9038d4eb160f9ea4dc9901b622d8'
             '39e4db3eed5dc522baffb7f853a7dbb7b417cc7a718599d768297adfbe99e263')
sha256sums+=('19f9500e685ad1472b430b428c76549d5ae5da958e0c5e6e155cdd477a39e357')
sha256sums_armv7h=('8d70fb5094f58aad98b601bbc42be354c2014b9fe734a1ee0b1e14bb041cc9cc'
                   '0e771370da68c855bfb4eaad4c2ae137883a474886a049b934dac2e775574cb9'
                   '2f586f72c34150330389854575a21be1d3ef3637c4f94bec2e948c2717a5aecb')

prepare() {
  cd "$pkgname-$pkgver"

  # handle patches
  local -a patches
  patches=($(printf '%s\n' "${source[@]}" | grep '.patch'))
  patches=("${patches[@]%%::*}")
  patches=("${patches[@]##*/}")

  if (( ${#patches[@]} != 0 )); then
    for patch in "${patches[@]}"; do
      if [[ $patch =~ revertme-* ]]; then
        msg2 "Reverting patch $patch..."
        patch -RNp1 < "../$patch"
      else
        msg2 "Applying patch $patch..."
        patch -Np1 < "../$patch"
      fi
    done
  fi


  ## Parabola changes ##

  # Generate the architecture-specific makepkg.conf files
  local carch chost cflags cxxflags ldflags ltoflags rustflags dbgflags dbgrustflags
  local options=() libdirs=()
  for carch in ${arch[*]}
  do  case ${carch} in
      aarch64)
        chost='aarch64-unknown-linux-gnu'
        cflags="-march=armv8-a                                           \
                -O2 -pipe -fstack-protector-strong -fno-plt -fexceptions \
                -Wp,-D_FORTIFY_SOURCE=3 -Wformat -Werror=format-security \
                -fstack-clash-protection                                 \
                -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"
        cxxflags="\$CFLAGS -Wp,-D_GLIBCXX_ASSERTIONS"
        ldflags='-Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now'
        ltoflags=""
        rustflags=""
        dbgflags='-g -fvar-tracking-assignments'
        dbgrustflags=""
        options=(strip docs !libtool !staticlibs emptydirs zipman purge debug !lto)
        libdirs=('lib:usr/lib')
        ;;
      armv7h)
        chost='armv7l-unknown-linux-gnueabihf'
        cflags="-march=armv7-a -mfloat-abi=hard -mfpu=neon               \
                -O2 -pipe -fstack-protector-strong -fno-plt -fexceptions \
                -Wp,-D_FORTIFY_SOURCE=3 -Wformat -Werror=format-security \
                -fstack-clash-protection                                 \
                -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"
        cxxflags="\$CFLAGS -Wp,-D_GLIBCXX_ASSERTIONS"
        ldflags='-Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now'
        ltoflags=""
        rustflags=""
        dbgflags='-g -fvar-tracking-assignments'
        dbgrustflags=""
        options=(strip docs !libtool !staticlibs emptydirs zipman purge debug !lto)
        libdirs=('lib:usr/lib')
        ;;
      i686)
        chost='i686-pc-linux-gnu'
        cflags="-march=i686 -mtune=generic -O2 -pipe -fno-plt -fexceptions \
                -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security   \
                -fstack-clash-protection -fcf-protection"
        cxxflags="\$CFLAGS -Wp,-D_GLIBCXX_ASSERTIONS"
        ldflags='-Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now'
        ltoflags="-flto=auto"
        rustflags=""
        dbgflags='-g'
        #dbgrustflags=
        options=(strip docs !libtool !staticlibs emptydirs zipman purge !debug !lto)
        #libdirs=()
        ;;
      x86_64)
        chost='x86_64-pc-linux-gnu'
        cflags="-march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions \
                -Wp,-D_FORTIFY_SOURCE=3 -Wformat -Werror=format-security     \
                -fstack-clash-protection -fcf-protection                     \
                -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"
        cxxflags="\$CFLAGS -Wp,-D_GLIBCXX_ASSERTIONS"
        ldflags="-Wl,-O1 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now \
                 -Wl,-z,pack-relative-relocs"
        ltoflags="-flto=auto"
        rustflags="-Cforce-frame-pointers=yes"
        dbgflags="-g"
        dbgrustflags="-C debuginfo=2"
        options=(strip docs !libtool !staticlibs emptydirs zipman purge debug lto)
        libdirs=('lib:usr/lib' 'lib32:usr/lib32')
        ;;
      esac

      sed < "${srcdir}"/makepkg.conf.in > "${srcdir}"/makepkg.conf.${carch} \
          -e "s|@CARCH@|${carch}|g"                                         \
          -e "s|@CHOST@|${chost}|g"                                         \
          -e "s|@CFLAGS@|${cflags}|g"                                       \
          -e "s|@CXXFLAGS@|${cxxflags}|g"                                   \
          -e "s|@LDFLAGS@|${ldflags}|g"                                     \
          -e "s|@LTOFLAGS@|${ltoflags}|g"                                   \
          -e "s|@RUSTFLAGS@|${rustflags}|g"                                 \
          -e "s|@DBGFLAGS@|${dbgflags}|g"                                   \
          -e "s|@DBGRUSTFLAGS@|${dbgrustflags}|g"                           \
          -e "s|@OPTIONS@|${options[*]}|g"                                  \
          -e "s|@LIBDIRS@|${libdirs[*]}|g"
  done

  # disable or neutralize tests which require networking
  local net_check_url=https://repo.parabola.nu/check_network_status.txt
  local fail_tests=() # eg: tests/sync-failover-404-with-body.py
  local sed_rx="s|xfail_tests = {|&$(printf "\\\n  '%s': true," "${fail_tests[@]}")|"

  if   (( ${#fail_tests[@]} )) && ! curl ${net_check_url} &> /dev/null
  then sed -i "${sed_rx}" test/pacman/meson.build
  fi
}

build() {
  cd "$pkgname-$pkgver"

  meson --prefix=/usr \
        --buildtype=plain \
        -Ddoc=enabled \
        -Ddoxygen=enabled \
        -Dscriptlet-shell=/usr/bin/bash \
        -Dldconfig=/usr/bin/ldconfig \
        build

  # FIXME: armv7h fails building doxygen
  # terminate called after throwing an instance of 'ghc::filesystem::filesystem_error'
  #   what():  Value too large for defined data type: '/build/pacman/src'
  # qemu: uncaught target signal 6 (Aborted) - core dumped
#  [[ "${CARCH}" != armv7h ]] || meson configure -Ddoxygen=disabled build

  meson compile -C build
}

check() {
  cd "$pkgname-$pkgver"

  meson test -C build
}

package() {
  cp "${srcdir}"/pacman.conf.${CARCH}  "${srcdir}"/pacman.conf  # minimize diff
  cp "${srcdir}"/makepkg.conf.${CARCH} "${srcdir}"/makepkg.conf # minimize diff

  cd "$pkgname-$pkgver"

  DESTDIR="$pkgdir" meson install -C build

  # install Arch specific stuff
  install -dm755 "$pkgdir/etc"
  install -m644 "$srcdir/pacman.conf" "$pkgdir/etc"
  install -m644 "$srcdir/makepkg.conf" "$pkgdir/etc"

  local wantsdir="$pkgdir/usr/lib/systemd/system/sockets.target.wants"
  install -dm755 "$wantsdir"

  local unit
  for unit in dirmngr gpg-agent gpg-agent-{browser,extra,ssh} keyboxd; do
    ln -s "../${unit}@.socket" "$wantsdir/${unit}@etc-pacman.d-gnupg.socket"
  done


  ## install Parabola specific stuff ##

  # pacman.d/dummy.conf
  install -dm755 "$pkgdir/etc/pacman.d"
  install -m644 "$srcdir/dummy.conf" "$pkgdir/etc/pacman.d/"

  # per-arch pacman.conf(s) and makepkg.conf(s)
  local carch
  install -dm755 "$pkgdir/usr/share/pacman/defaults"
  for carch in ${arch[*]}
  do  install -m644 "$srcdir/pacman.conf.$carch" "$pkgdir/usr/share/pacman/defaults/"
      install -m644 "$srcdir/makepkg.conf.$carch" "$pkgdir/usr/share/pacman/defaults/"
  done
}
