#!/bin/bash

function build-with-aurutils() {
  aur build -c
}

function build-with-makepkg() {
  makepkg -Ccsr

  case "$?" in
  0)
    # Copy the build package to /home/custompkgs
    cp --no-clobber "${PKG}-"*.pkg.tar.zst /home/custompkgs/ || return $?
    ;;
  13)
    # Exit code 13: A package has already been built.
    return 0
    ;;
  *)
    # Some other makepkg error occurred.
    return 1
    ;;
  esac
}

function build-pkg() {
  # $1: package-name
  local PKG
  PKG="$1"

  # Check if PKGBUILD exists, otherwise skip
  [ -f "../pkg/${PKG}/PKGBUILD" ] || {
    echo "Directory ../pkg/${PKG} does not contain a PKGBUILD file - skipping it!";
    SKIPPED_PKGS+=("${PKG}");
    return 0;
  }

  cd "../pkg/${PKG}" || return $?

  # Build and copy to /home/custompkgs
#   build-with-makepkg || {
  build-with-aurutils || {
    echo "Failed to build package ${PKG}!";
    return 1
  }

  cd ../../build-pkg || return $?
}

function push-pkg() {
  arch-repo-push-new || return $?  # Push remote repository
  echo "Running 'pacman -Sy' to update de-p1st mirror database ..."
  sudo pacman -Sy || return $?
}

function build-and-push() {
  for PKG in "$@"; do
    build-pkg "${PKG}" || return $?
  done
  push-pkg || return $?
}

function space_separated_to_array() {
  # arg $1: name of variable with space separated list
  # arg $2: name of array to store values into

  local -n ptr=$1  || return $?
  local -n ptr2=$2 || return $?
  # ptr space separated list.
  # Store this as array ptr2.
  # Without newline at last array element: https://unix.stackexchange.com/a/519917/315162
  # shellcheck disable=SC2034
  readarray -d " " -t ptr2 < <(printf '%s' "$ptr")
}

function main() {
  # Usage:
  #   Without arguments: Build all packages and watch out for dependencies between them:
  #     First build packages on wich others depend
  #     Then add them to de-p1st mirror
  #     And repeat these steps until all packages are built
  #   First argument "all": Build all packages, ordered by name
  #   Multiple arguments: Build the the specified packages in their given order

  SKIPPED_PKGS=()

  if [ "$1" = "all" ]; then
    for PKG in ../pkg/*; do
      build-pkg "$(basename "${PKG}")" || return $?
    done
  elif [ "$#" -gt "0" ]; then
    # List of packages is given as arguments
    for PKG in "$@"; do
      build-pkg "$PKG" || return $?
    done
  else
    PKGLIST=pkglist-AUR.txt  # TODO

    mapfile -t STAGES < "${PKGLIST}"
    # shellcheck disable=SC2034
    for line in "${STAGES[@]}"; do
      space_separated_to_array line pkgs
      # shellcheck disable=SC2154
      build-and-push "${pkgs[@]}" || exit $?
    done
  fi

  push-pkg || return $?

  if [ "${#FAILED_PKGS[@]}" -gt "0" ]; then
    echo ""
    echo "Warning: Some packages were skipped: ${SKIPPED_PKGS[*]}"
    return 1
  fi
}

main "$@"
