#!/bin/bash
set -euo pipefail

BASE_URL="https://koji-proxy.atm.svcs.io/pub/els-alt/repository-package-name-tools/repository-package-name-lists"

# Remote subdirectories
DIR_PREFIXES="additional-pkg-prefixes-alt"
DIR_IGNORE="additional-pkg-prefixes-ignore_prefix_dep-alt"

# Stable local names (must match Source tags in .spec)
OUT_PREFIXES="additional-pkg-prefixes-alt"
OUT_IGNORE="additional-pkg-prefixes-ignore-prefix-dep-alt"

# BUILD_PLATFORM must be provided by the build system
if [[ -z "${BUILD_PLATFORM:-}" ]]; then
  echo "error: BUILD_PLATFORM hasn't set"
  exit 1
fi

die() { echo "error: $*" >&2; exit 1; }

platform="${BUILD_PLATFORM,,}"

# Detect arch from platform suffix if present (e.g. Alma8_x86_64)
arch_from_platform="$(echo "$platform" | sed -n 's/.*_\([a-z0-9]\+\)$/\1/p')"
arch="$(uname -m)"
[[ "$arch" == "amd64" ]] && arch="x86_64"
if [[ "$arch_from_platform" == "x86_64" || "$arch_from_platform" == "aarch64" || "$arch_from_platform" == "arm64" ]]; then
  [[ "$arch_from_platform" == "arm64" ]] && arch="aarch64" || arch="$arch_from_platform"
fi

# Determine distro family: debian | ubuntu | el
# Rule: any EA4_* is treated as CloudLinux (EL)
case "$platform" in
  *ea4*) distro="el" ;;
  debian*) distro="debian" ;;
  ubuntu*) distro="ubuntu" ;;
  el*|cloudlinux*|centos*|almalinux*|alma*) distro="el" ;;
  *) die "unsupported BUILD_PLATFORM=${BUILD_PLATFORM}" ;;
esac

# Extract numeric version part from BUILD_PLATFORM
# Rule: EA4_* uses the number after underscore (EA4_9 -> 9)
if [[ "$platform" == *ea4* ]]; then
  ver="$(echo "$platform" | sed -n 's/.*ea4[_-]\([0-9]\+\).*/\1/p')"
else
  ver="$(echo "$platform" | sed -n 's/^[a-z]\+\([0-9]\+\).*/\1/p')"
fi
[[ -n "$ver" ]] || die "cannot extract version from BUILD_PLATFORM=${BUILD_PLATFORM}"

# Build filenames for both lists
if [[ "$distro" == "ubuntu" ]]; then
  # Ubuntu requires X.Y (e.g. 16.04). Supports ubuntu2004 and ubuntu16_04 forms.
  if [[ "$ver" =~ ^[0-9]{4}$ ]]; then
    major="${ver:0:2}"
    minor="${ver:2:2}"
  else
    major="$ver"
    minor="$(echo "$platform" | sed -n 's/.*_\([0-9]\+\).*/\1/p')"
    [[ -n "${minor:-}" ]] || die "ubuntu version must include minor (e.g. ubuntu16_04)"
    [[ "$minor" =~ ^[0-9]$ ]] && minor="0${minor}"
  fi
  fn_prefixes="repo-ubuntu${major}.${minor}-stable-packages.txt"
  fn_ignore="repo-ubuntu${major}.${minor}-stable-ignore-prefix-dep.txt"

elif [[ "$distro" == "debian" ]]; then
  fn_prefixes="repo-debian${ver}-stable-packages.txt"
  fn_ignore="repo-debian${ver}-stable-ignore-prefix-dep.txt"

else
  fn_prefixes="repo-el${ver}-stable-${arch}-packages.txt"
  fn_ignore="repo-el${ver}-stable-${arch}-ignore-prefix-dep.txt"
fi

url1="${BASE_URL}/${DIR_PREFIXES}/${fn_prefixes}"
url2="${BASE_URL}/${DIR_IGNORE}/${fn_ignore}"

echo "BUILD_PLATFORM=${BUILD_PLATFORM}"
echo "Resolved distro=${distro}, version=${ver}, arch=${arch}"
echo "Fetching prefixes: ${url1}"
echo "Fetching ignore:   ${url2}"

# Download helper: try curl first, then wget
download() {
  local u="$1" out="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$u" -o "$out"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$out" "$u"
  else
    die "curl or wget is required (add curl to buildsys-pre-build.yml dependencies)"
  fi
}

tmp1="$(mktemp)"
tmp2="$(mktemp)"

download "$url1" "$tmp1"
download "$url2" "$tmp2"

[[ -s "$tmp1" ]] || die "downloaded file is empty: $url1"
[[ -s "$tmp2" ]] || die "downloaded file is empty: $url2"

# Place files next to this script (repo root), as required by the build system
cp -f "$tmp1" "./${OUT_PREFIXES}"
cp -f "$tmp2" "./${OUT_IGNORE}"
chmod 0644 "./${OUT_PREFIXES}" "./${OUT_IGNORE}"

# Optional: keep debug copies
mkdir -p ./_injected
cp -f "$tmp1" "./_injected/${OUT_PREFIXES}"
cp -f "$tmp2" "./_injected/${OUT_IGNORE}"
chmod 0644 "./_injected/${OUT_PREFIXES}" "./_injected/${OUT_IGNORE}"

rm -f "$tmp1" "$tmp2"

echo "Injected file path(s):"
echo "  ./${OUT_PREFIXES}"
echo "  ./${OUT_IGNORE}"
