#!/bin/bash

BASE_DIR="/run/mpa/"

__print_usage() {
	echo ""
	echo "voxl-list-pipes"
	echo ""
	echo "List all of the available MPA pipes"
	echo ""
	echo "Options:"
	echo -e "\t-h|--help        : Show this help message"
	echo -e "\t-t <type>        : Show only pipes of this type"
	echo ""
}

__contains_word () {
        local w word=$1; shift
        for w in "$@"; do
                [[ $w = "$word" ]] && return 0
        done
        return -1
}

__mode_types() {
    shopt -s nullglob
    local f base typ
    declare -A MAP

    # Normalize BASE_DIR to include a trailing slash
    [[ "${BASE_DIR}" != */ ]] && BASE_DIR="${BASE_DIR}/"

    # One pass over all info files
    for f in "${BASE_DIR}"*/info; do
        # Prefer jq (robust JSON); fall back to awk if jq missing or fails
        if command -v jq >/dev/null 2>&1; then
            typ=$(jq -r 'try .type // empty' "$f" 2>/dev/null)
        fi
        if [[ -z "$typ" ]]; then
            typ=$(sed -n 's/.*"type"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$f")
        fi
        [[ -n "$typ" ]] || continue

        base=$(basename "$(dirname "$f")")
        MAP["$typ"]+=$'\t'"$base"$'\n'
    done

    # Print types in sorted order with their files
    if ((${#MAP[@]})); then
        printf '%s\0' "${!MAP[@]}" \
          | sort -z \
          | while IFS= read -r -d '' typ; do
                printf '%s\n' "$typ"
                printf '%s' "${MAP[$typ]}"
                printf '\n'
            done
    fi
}



__list_pipes_main() {

    MODE=1

    for (( i=1; i <= "$#"; i++ )); do

        PREV_NUM=$(($i-1))
        ARG=${!i}
        PREV_ARG=${!PREV_NUM}

        #echo "arg position: ${i}"
        #echo "arg value: ${!i}"

        case $ARG in

            --mode-types|-t)
                MODE=1
                ;;

            --help|-h)
                __print_usage
                exit 0
                ;;

            *)
                case $PREV_ARG in

                    --mode-types|-t)
                        MODE="$ARG"
                        ;;

                    *)
                        echo "Unknown Option: $ARG"
                        __print_usage
                        exit -1
                esac

        esac
    done

    case $MODE in

        # 0)
        # 	# Default behavior
        # 	# Effectively the same as ls but formats it line by line
        # 	for file in ${BASE_DIR}* ; do
        # 		echo -e "$(basename $file)"
        # 	done
        #     ;;
        1)
            #Sort by types Mode
            __mode_types
            ;;
        *)
            #Show only specific type
            for file in ${BASE_DIR}* ; do
                if [ -f "${file}/info" ] && cat "${file}/info" | grep -q "\"${MODE}\"" ; then
                    echo -e "$(basename $file)"
                fi
            done
            ;;
    esac
}

__list_pipes_main $@
