#!/bin/bash

source /etc/de-p1st-repo/arch-repo.cfg || exit $?
# Enable nullglob for the case that not all patterns match, e.g. just *.zst but not *.xz packages exist.
shopt -s nullglob

function main() {
  cd "${LOCAL_PKG_DIR}" || return $?

  # Check if at least one matching file exists
  match="0"
  for PKG in ./*.pkg.tar.{xz,zst}; do
      # There is at least one match!
      match="1"
      break
  done

  if [ "$match" = "0" ]; then
    echo "There are no local packages inside ${LOCAL_PKG_DIR}"
    return 0
  fi


  # Get list of new packages, one package per line.
  rsync --ignore-existing --out-format="%n" --dry-run \
    ./*.pkg.tar.{xz,zst} "${REMOTE_SSH_HOST}":"${REMOTE_PKG_DIR}" > new-pkg.txt || return $?

  # If there are no new packages to push/synchronize, then return
  if [ ! -s new-pkg.txt ]; then
    echo "No new packages inside ${LOCAL_PKG_DIR}";
    return 0;
  fi


  # Transfer new packages using rsync
  rsync --ignore-existing --progress --human-readable \
    ./*.pkg.tar.{xz,zst} "${REMOTE_SSH_HOST}":"${REMOTE_PKG_DIR}" || return $?

  # Transfer new-pkg.txt
  rsync --ignore-times --checksum --progress --human-readable \
    new-pkg.txt "${REMOTE_SSH_HOST}":"${REMOTE_PKG_DIR}" || return $?


  # Add each new package to database
  ssh "${REMOTE_SSH_HOST}" "/usr/bin/arch-repo-receive-new" || return $?
}


for LOCAL_PKG_DIR in "${LOCAL_PKG_DIRS[@]}"; do
  main
done
