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

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
}

#
# 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|^de-p1st\s*||; s|\s*\[installed.*\]\s*$||') || return $?
}

main "$@"
