#!/bin/bash

. /usr/bin/altera-sh-functions

shopt -s nullglob

installed_modules()
{
    local directory=$1 entry name LC_ALL=C

    [[ -e $directory ]] || return 0
    [[ -d $directory && -r $directory && -x $directory ]] || return 1

    for entry in "$directory"/*; do
        name=${entry##*/}
        # Match the module names accepted by the Altera router.
        if [[ $name =~ ^[A-Za-z0-9_-]*[A-Za-z0-9][A-Za-z0-9_-]*$ &&
              -f $entry && -x $entry ]]; then
            printf '%s\n' "$name"
        fi
    done
}

on_list()
{
    local root=/usr/lib/alterator backend3 backend4

    if [[ $in_action_payload != '{}' ]]; then
        write_error_json "list expects an empty object"
        return 1
    fi

    if ! backend3=$(installed_modules "$root/backend3") ||
       ! backend4=$(installed_modules "$root/backend4"); then
        write_error_json "could not scan backend directories"
        return 1
    fi

    jq -cn --arg backend3 "$backend3" --arg backend4 "$backend4" '
        def modules: split("\n") | sort;
        {backend3: ($backend3 | modules), backend4: ($backend4 | modules)}
    ' | write_json
}

message_loop_backend4
