#!/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

  MAKEPKG_ARGS=('--syncdeps')
  if [ "${INTERACTIVE}" != "true" ]; then
      MAKEPKG_ARGS+=('--noconfirm')  # --noconfirm is passed to pacman
  fi

  # Build the package.
  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.
      exit ${saved}
      ;;
  esac
}

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

  # Refresh mirrors
  sudo pacman -Sy

  if [ "${1}" = "interactive" ]; then
    INTERACTIVE=true
    shift;  # remove first argument
  fi

  # If first argument is zero, use default directory
  if [ -z "${1}" ]; then
    PKG=/pkg
    echo "No argument given. Using default directory ${PKG} to look for PKGBUILD ..."
  # Else append argument $1 as relative path
  else
    PKG=/pkg/"${1}"
    echo "Looking for PKGBUILD in ${PKG} ..."
  fi

  build-pkg

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

main "$@"
