#!/usr/bin/with-contenv bashio
# shellcheck shell=bash

declare -a args

# Network: bind to all interfaces, allow all connections
args+=(--http-addresses "0.0.0.0:7396")
args+=(--allow "0/0")

# FAH account credentials
FAH_USER=$(bashio::config 'user')
TEAM=$(bashio::config 'team')
PASSKEY=$(bashio::config 'passkey')
ACCOUNT_TOKEN=$(bashio::config 'account_token')
MACHINE_NAME=$(bashio::config 'machine_name')

if bashio::config.has_value 'user'; then
    args+=(--user "${FAH_USER}")
fi

if bashio::config.has_value 'team'; then
    args+=(--team "${TEAM}")
fi

if bashio::config.has_value 'passkey'; then
    args+=(--passkey "${PASSKEY}")
fi

if bashio::config.has_value 'account_token'; then
    args+=(--account-token "${ACCOUNT_TOKEN}")
    if bashio::config.has_value 'machine_name'; then
        args+=(--machine-name "${MACHINE_NAME}")
    fi
fi

if ! bashio::config.has_value 'user' && ! bashio::config.has_value 'account_token'; then
    bashio::log.info "No user or account_token set — folding anonymously."
fi

# Run from /config so fah-client stores its data there
mkdir -p /config
cd /config || exit 1

exec /app/fah-client "${args[@]}"
