#!/usr/bin/env bash
set -euo pipefail

: "${RELEASE_TAG:?Missing RELEASE_TAG}"
: "${TAG_PREFIX:?Missing TAG_PREFIX}"
: "${ASSETS_DIR:?Missing ASSETS_DIR}"
: "${RPM_BINARY_DIR:?Missing RPM_BINARY_DIR}"
: "${RPM_BINARY_PATTERN_PREFIX:?Missing RPM_BINARY_PATTERN_PREFIX}"
: "${RPM_DISTRO_NAME:?Missing RPM_DISTRO_NAME}"
: "${RPM_DISTRO_VERSION:?Missing RPM_DISTRO_VERSION}"
: "${GITHUB_ENV:?Missing GITHUB_ENV}"

version="${RELEASE_TAG#${TAG_PREFIX}}"
if [[ -z "$version" || "$version" == "$RELEASE_TAG" ]]; then
  echo "Expected tag in the form ${TAG_PREFIX}{version}, got: $RELEASE_TAG" >&2
  exit 1
fi

if [[ -n "${EXPECTED_VERSION:-}" && "$EXPECTED_VERSION" != "$version" ]]; then
  echo "Release tag version ($version) does not match expected package version ($EXPECTED_VERSION)." >&2
  exit 1
fi

rm -rf "$ASSETS_DIR"
mkdir -p "$ASSETS_DIR"

found=0
binary_pattern="${RPM_BINARY_PATTERN_PREFIX}${version}-*.rpm"
if [[ -d "$RPM_BINARY_DIR" ]]; then
  find_cmd=(
    find "$RPM_BINARY_DIR" -type f -name "$binary_pattern"
  )
  while IFS= read -r exclude; do
    [[ -n "$exclude" ]] || continue
    find_cmd+=( ! -name "$exclude" )
  done <<< "${RPM_BINARY_EXCLUDE_PATTERNS:-}"
  find_cmd+=( -exec cp '{}' "$ASSETS_DIR/" ';' )
  "${find_cmd[@]}"
fi

if find "$ASSETS_DIR" -maxdepth 1 -type f -name '*.rpm' | grep -q .; then
  found=1
fi

if [[ -n "${RPM_SOURCE_DIR:-}" && -n "${RPM_SOURCE_PATTERN_PREFIX:-}" && -d "$RPM_SOURCE_DIR" ]]; then
  source_pattern="${RPM_SOURCE_PATTERN_PREFIX}${version}-*.src.rpm"
  find "$RPM_SOURCE_DIR" -type f -name "$source_pattern" -exec cp '{}' "$ASSETS_DIR/" ';'
fi

if [[ "$found" -ne 1 ]]; then
  echo "No RPM artifacts were produced." >&2
  exit 1
fi

package_group="${RPM_PACKAGE_GROUP:-}"

{
  printf 'RELEASE_VERSION=%s\n' "$version"
  printf 'RELEASE_ASSETS_DIR=%s\n' "$ASSETS_DIR"
  printf 'RPM_PACKAGE_GROUP=%s\n' "$package_group"
} >> "$GITHUB_ENV"
