#!/usr/bin/env bash
BUILDER_NO_INCLUDE_SRPM=${BUILDER_NO_INCLUDE_SRPM:-0}
SPEC_FILE=$1
shift

set -euo pipefail

if [ "$SPEC_FILE" == "" ] ; then
  echo "No spec file selected"
  exit 1
fi

group_start() {
	WHAT=$1
	shift
  printf "::group:: ===%s===\n" "$WHAT"
  set -x
}
group_end() {
  set +x
	printf "::endgroup::\n"
}

group_start "Generate spec file with rpkg"
OUTDIR="$(mktemp -d)"
SPEC_PATH="$(realpath "$(dirname "$SPEC_FILE")")"
rpkg --path "${SPEC_PATH}" spec --outdir "$OUTDIR"
RPMSPEC_FOR_CHECK="$(mktemp)"
rpmspec -P "${OUTDIR}"/*.spec | tee "${RPMSPEC_FOR_CHECK}"
if grep "ExclusiveArch:" "${RPMSPEC_FOR_CHECK}" ; then
  if ! grep "$(arch)" "${RPMSPEC_FOR_CHECK}" ; then
    echo "Arch Skipped" | tee /tmp/sources/arch_skipped
    exit 0
  fi
fi
group_end

group_start "Lint spec file (non-blocking)"
set +euo pipefail
rpmlint "${OUTDIR}/*.spec"
set -euo pipefail
group_end

group_start "Fetch sources and generate srpm"
spectool -ag "${OUTDIR}"/*.spec -C "${OUTDIR}"
rpkg --path "${SPEC_PATH}" srpm --outdir "${OUTDIR}"
ls -lah "${OUTDIR}"
group_end

group_start "Build RPM with mock"
if [ "$BUILDER_NO_INCLUDE_SRPM" != "1" ] ; then
  mock --isolation=simple "$OUTDIR"/*.src.rpm "$@"
else
  mock --isolation=simple "$@"
fi
group_end
