#!/bin/sh

# Turn on libshell verbose mode
verbose=1

# Require libshell
. shell-error
. shell-quote
. shell-config
. shell-var

readonly RD_PROFILES_DIR="/etc/alterator-rd/"
readonly RD_USERS_CFG_DIR="$RD_PROFILES_DIR/users/"

list_profiles() {
    local IAM="$1"
    local config="$RD_USERS_CFG_DIR/$IAM"

    if ! [ -f "$config" -a -r "$config" ]; then
        fatal "Can't find configuration file $config"
    fi

        # Fork sub-shell to preserve virgin env
        (
        . "$config"

        if [ ${#RD_PROFILES[*]} -eq 0 ]; then
            verbose "No available profiles"
            exit 0
        fi

        verbose "Available profiles:"
        for profile in "${RD_PROFILES[@]}"; do
            if ! [ -f "$RD_PROFILES_DIR/$profile" -a -r "$RD_PROFILES_DIR/$profile" ]; then
                verbose "Profile \`$profile' listed, but not defined."
                continue
            fi
            echo "$profile"
        done
        )
}

# Lookup who we are
if [ -n "$USER" ]; then
    IAM="$USER"
elif [ -n "$USERNAME" ]; then
    IAM="$USERNAME"
elif [ -n "$LOGNAME" ]; then
    IAM="$LOGNAME"
fi

verbose "I am: $IAM"

if [ -z "$IAM" ]; then
    fatal "Can't guess my system user name."
fi

list_profiles "$IAM"
