#!/bin/bash
#
# For all packages in repository $REMOTE_DB_NAME,
# compare package version with AUR and
# print all outdated packages
#

source /usr/lib/de-p1st-repo/util.sh    || exit $?
source /usr/lib/de-p1st-repo/pkgver.sh  || exit $?
source /usr/lib/de-p1st-repo/pkginfo.sh || exit $?
source /etc/de-p1st-repo/arch-repo.cfg  || exit $?



function main(){
  echo "Note: You may run 'arch-repo-push-new' and 'pacman -Sy' first ..."

  all_pkg_vers      || return $?
  check_aur_updates || return $?

  if [ "${#AUR_UPDATES[@]}" -gt "0" ]; then
    echo "Repository ${REMOTE_DB_NAME} contains packages with available AUR updates:"
    for AUR_PKG in "${AUR_UPDATES[@]}"; do
      echo "  ${AUR_PKG}"
    done
  else
    echo "There are no pending AUR updates in repository ${REMOTE_DB_NAME}."
  fi

  get_vcs_packages || return $?
  if [ "${#VCS_PKGS[@]}" -gt "0" ]; then
    echo ""
    echo "Note: Some VCS packages were found which are possibly outdated:"
    printf "VCS_PKGS=(%s)\n" "${VCS_PKGS[*]}"
  fi
}

function get_vcs_packages(){
  # return: array GIT_PKGS with all VCS packages
  VCS_PKGS=()

  # https://wiki.archlinux.org/title/VCS_package_guidelines#VCS_sources
  # https://github.com/AladW/aurutils/pull/283/files
  readonly AURVCS='.*-(bzr|git|hg|svn)$'

  while IFS= read -r PKG_VER; do
    PKGNAME=$(first_word "${PKG_VER}") || return $?
    if echo "${PKGNAME}" | grep -E "$AURVCS" >/dev/null; then
      VCS_PKGS+=("${PKGNAME}")
    fi
  done <<< "${PKG_VERS}"
}

#
# Store packages from $PKG_VERS with available AUR updates in $AUR_UPDATES.
# $AUR_UPDATES is an array where each entry describes one outdated package with it's current and new version.
#
function check_aur_updates(){
  mapfile -t AUR_UPDATES < <(echo "$PKG_VERS" | aur vercmp)
}

#
# Store all installed package names and their versions
# from repository $REMOTE_DB_NAME
# in variable $PKG_VERS.
# $PKG_VERS consists of multiple lines in the format: "<pkgname><whitespace><pkgver>"
#
function installed_pkg_vers(){
  # The paclist script is partof the package "pacman-contrib"
  PKG_VERS=$(paclist "${REMOTE_DB_NAME}") || return $?
}

#
# Store all package names and their versions
# from repository $REMOTE_DB_NAME
# in variable $PKG_VERS.
# $PKG_VERS contains of multiple lines in the format: "<pkgname><whitespace><pkgver>"
#
function all_pkg_vers(){
  PKG_VERS=$(pacman -S --list "${REMOTE_DB_NAME}" | sed "s|^${REMOTE_DB_NAME}\\s*||; s|\\s*\\[installed.*\\]\s*\$||") || return $?
}

main "$@"
