#!/bin/bash
# SPDX-FileCopyrightText: 2025 Torsten Keßler <tpkessler@archlinux.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

function help() {
  local -r COMMAND=${BASH_SOURCE[0]##*/}
  cat <<-__EOF__
        Usage: ${COMMAND} [OPTIONS]

        Print supported GPU targets for ROCm packages on Arch Linux

        OPTIONS
        -d        Delimiter for GPU architecture list
        -e        Exclude archictures, separated by comma
        -s        Simplified list of architectures without xnack prefix
        -h        Show this help
__EOF__
}

function die() {
  >2 echo $1
  exit "${2:-1}"
}

function supported() {
  # Following Fedora's list,
  # https://src.fedoraproject.org/rpms/rocm-rpm-macros/blob/rawhide/f/macros.rocm#_3
  local gfx=(
    gfx9-generic
    gfx942
    gfx950
    gfx1010
    gfx1012
    gfx1030
    gfx1031
    gfx1035
    gfx1036
    gfx1100
    gfx1101
    gfx1102
    gfx1103
    gfx1150
    gfx1151
    gfx1152
    gfx1153
    gfx1170
    gfx1200
    gfx1201
    gfx1250
  )

  declare -A lookup
  for target in "${EXCLUDE[@]}"; do
    lookup[$target]=1
  done
  for idx in "${!gfx[@]}"; do
    [ "${lookup[${gfx[$idx]}]:-}" ] && unset 'gfx[idx]'
  done
  gfx=("${gfx[@]}")

  local output
  printf -v output "%s$DELIM" "${gfx[@]}"
  if [ $SIMPLIFIED -gt 0 ]; then
    echo "${output%${DELIM}}" | sed 's/:xnack[+-]//g'
  else
    echo "${output%${DELIM}}"
  fi
}

DELIM=";"
EXCLUDE=()
SIMPLIFIED=0
while getopts "d:e:sh" opt; do
  case $opt in
    h)
      help
      exit 0
      ;;
    d)
      DELIM=$OPTARG
      ;;
    e)
      EXCLUDE=($(echo "$OPTARG" | tr ',' '\n'))
      ;;
    s)
      SIMPLIFIED=1
      ;;
    *)
      help
      die "Invalid option -- '${OPTARG:-${!OPTIND:-${opt:-}}}'" 1
      ;;
  esac
done

supported DELIM
