#!/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
        -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=(
        gfx900
        gfx906:xnack-
        gfx908:xnack-
        gfx90a:xnack+
        gfx90a:xnack-
        gfx942
        gfx950
        gfx1010
        gfx1012
        gfx1030
        gfx1031
        gfx1035
        gfx1100
        gfx1101
        gfx1102
        gfx1103
        gfx1150
        gfx1151
        gfx1152
        gfx1153
        gfx1200
        gfx1201
    )

    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[@]}"
    echo "${output%${DELIM}}"
}

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

supported DELIM
