#!/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/"

additional_info() {
    local user="$1" && shift
    local prof="$1" && shift
    local user_config="$RD_USERS_CFG_DIR/$user"
    
    if ! [ -f "$user_config" -a -r "$user_config" ]; then
        fatal "Can't find configuration file $user_config"
    fi

    # Fork sub-shell to preserve virgin env
    (
    local autostart="0"
    . "$user_config"

    for p in "${RD_AUTOSTART[@]}"; do
        if [ "$prof" = "$p" ]; then
            autostart="1"
        fi
    done

    echo "autostart $autostart"
    )
}

if [ ${#*} -ne 1 ]; then
    fatal "Use: $PROG <profile>"
fi

readonly profile="$RD_PROFILES_DIR/$1"

if ! [ -f "$profile" -a -r "$profile" ]; then
    fatal "Can't fin'd profile \`$profile'."
fi

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

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

verbose "I am: $IAM"

eval protocol="$(shell_config_get "$profile" PROTOCOL)"
if [ -z "$protocol" ]; then
    fatal "Can't lookup protocol type for \`$profile'."
fi

# Print protocol type
echo "$protocol"

# Lookup additional info for profile
additional_info "$IAM" "$(basename "$profile")"
