#!/bin/bash
set -e

DEFAULT_MAKEPKG_ARGS=('--syncdeps' '--noconfirm')

#################################

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

  PKG=/pkg/"${1}"
  shift;  # remove first arg
  echo "Looking for PKGBUILD in ${PKG} ..."

  build-pkg "$@"

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

function build-pkg(){
  # Make a copy as we don't want to change stuff inside "/pkg"
  cp -r "${PKG}" /tmp/pkg
  cd /tmp/pkg

  MAKEPKG_ARGS=()
  if [ "${#DEFAULT_MAKEPKG_ARGS[@]}" -gt 0 ]; then
    MAKEPKG_ARGS+=("${DEFAULT_MAKEPKG_ARGS[@]}")
  fi
  if [ $# -gt 0 ]; then
    MAKEPKG_ARGS+=("$@")
  fi

  # Build the package.
  echo "Running: makepkg ${MAKEPKG_ARGS[*]}"
  # Disable exit on error as we manually check the exit status in a switch-case
  set +e
  makepkg "${MAKEPKG_ARGS[@]}"; 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.
      echo "Error during build of package ${PKG}!"
      exit ${saved}
      ;;
  esac
}

main "$@"