#!/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!";
    FAILED_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}!";
    FAILED_PKGS+=("${PKG}");
  }

  cd ../..        || return $?
}


function build-all() {
  for PKG in pkg/*; do
    build-pkg "$(basename "${PKG}")" || return $?
  done
}

function main() {
  # Usage:
  #   Either zero arguments to build all packages
  #   or the names of the packages to build as arguments

  FAILED_PKGS=()


  if [ "$#" -gt "0" ]; then
    # At least one argument is given

    for PKG in "$@"; do
      build-pkg "$PKG" || return $?
    done

  else
    # No arguments given
    build-all || return $?
  fi

  # Push remote repository
  echo ""
  arch-repo-push-new || exit

  if [ "${#FAILED_PKGS[@]}" -gt "0" ]; then
    echo ""
    echo "Warning: Not all packages were build successfully: ${FAILED_PKGS[*]}"
    return 1

  fi
}

main "$@"