#!/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 ../..        || 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 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
    # Stage1
    build-and-push xorg-meta de-p1st-locale de-p1st-systemd de-p1st-sudo de-p1st-screen de-p1st-htop de-p1st-pacman de-p1st-pacman-mirrorlist de-p1st-networkmanager de-p1st-ucode-placeholder de-p1st-ucode-intel de-p1st-ucode-amd de-p1st-nano de-p1st-mkinitcpio de-p1st-makepkg de-p1st-grub de-p1st-font de-p1st-keyboard-de de-p1st-keyboard-x11-de de-p1st-gnupg de-p1st-redshift de-p1st-theme de-p1st-sddm-autologin-placeholder de-p1st-sddm-autologin-yoda de-p1st-sddm-theme-nordic de-p1st-gpu-generic de-p1st-gpu-amdgpu de-p1st-installer de-p1st-repo || return $?
    # Stage2
    build-and-push de-p1st-smartcard de-p1st-kernel-default de-p1st-kernel-lts de-p1st-dns || return $?
    # Stage3
    build-and-push de-p1st-base || return $?
    # Stage4
    build-and-push de-p1st-xfce4 || return $?
    # Stage5
    build-and-push de-p1st-xfce4-hidpi || return $?
  fi

  push-pkg || return $?

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

main "$@"
