#!/bin/sh -e

all_types=`dpkg-architecture --help 2>&1 | grep "^Known GNU" | \
  cut -d " " -f 6- | sed "s/, / /g"`

all_cpus=`echo ${all_types} | tr " " "\n" | cut -d "-" -f 1 | sort | uniq`
all_systems=`echo ${all_types} | tr " " "\n" | cut -d "-" -f 2-  | sort | uniq`

if [ "$#" = "0" ] ; then
  echo "Known cpus: `for i in ${all_cpus} ; do echo -n $i\  ; done`"
  echo "Known systems: `for i in ${all_systems} ; do echo -n $i\  ; done`"
  exit
fi

case "$1" in
  "-n"|"--negated") negated="true" ; shift ;;
  *) negated="false"
esac
cpus="$1"
systems="$2"

# "any" wildcards
if [ "${cpus}" = "any" ] ; then
  cpus=`for i in ${all_cpus}; do echo -n $i, ; done`
fi
if [ "${systems}" = "any" ] ; then
  systems=`for i in ${all_systems}; do echo -n $i, ; done`
fi

# replace commas with spaces
cpus="`echo ${cpus} | sed "s/,/ /g"`"
systems="`echo ${systems} | sed "s/,/ /g" | sed "s/linux-gnu/linux/g"`"

# for each concievable type..
(for cpu in ${all_cpus} ; do for system in ${all_systems} ; do
  # if it's in our list..
  if echo " ${cpus} " | grep -q " ${cpu} " && echo " ${systems} " | grep -q " ${system} " ; then
    # and we're not in negated mode..
    if ! `${negated}` ; then
      # if it exists..
      if arch=`dpkg-architecture -f -t${cpu}-${system} -qDEB_HOST_ARCH 2>/dev/null` ; then
        echo -n " ${arch}"
      fi
    fi
  # if not in our list..
  else
    # but we are in negated mode..
    if `${negated}` ; then
      # if it exists..
      if arch=`dpkg-architecture -f -t${cpu}-${system} -qDEB_HOST_ARCH 2>/dev/null` ; then
        echo -n " ${arch}"
      fi
    fi
  fi
done ; done) | cut -c 2-
echo

