#!/bin/bash
#
# For each ARG in ARGUMENTS
# build /pkg/$ARG/PKGBUILD
# and store the built package at /out/
#
# If no ARGUMENTS are given, then fallback to path /pkg/PKGBUILD
#
set -e

function build-pkg(){
  # Make a copy as "/pkg" might be read-only and we do not want to alter it
  cp -r "${PKG}" /tmp/pkg
  cd /tmp/pkg

  # Build the package.
  # One could add argument "--noconfirm" to "makepkg" (which will be passed to Pacman) for non-interactive mode.
  set +e
  makepkg --syncdeps
  saved="$?"
  set -e

  case "${saved}" in
    "0")
      # Exit code 0, no error occurred.
      true
      ;;
    "13")
      # Exit code 13: A package has already been built.
      true  # Skip already built packages!
      ;;
    *)
      # Exit with exit-code from makepkg.
      exit ${saved}
      ;;
  esac
}

function main(){
  # Write-permission for user "build"
  sudo chown "build:wheel" /out


  # Refresh mirrors
  sudo pacman -Sy

  # If first argument is zero, use default directory
  if [ -z "${1}" ]; then
    PKG=/pkg
    echo "No argument given. Using default ${PKG} directory to look for PKGBUILD ..."
    build-pkg
  # Else repeat fo for each argument
  else
    for RELATIVE_PKG_DIR in "$@"; do
      PKG=/pkg/"${RELATIVE_PKG_DIR}"
      echo "Looking for PKGBUILD in ${PKG} ..."
      build-pkg
    done
  fi

  # Ensure permissions match those of the original PKGBUILD.
  sudo chown "$(stat -c '%u:%g' "${PKG}"/PKGBUILD)" /out/*.pkg.tar.*
}

main "$@"