#!/usr/bin/env bash
set -euo pipefail

# Buzz's managed-agent harness accepts one MCP executable per agent. Keep the
# Mealie credential out of the agent definition by loading only the three
# variables this server understands from the existing Hermes dotenv file.
mealie_env_file="${MEALIE_ENV_FILE:-${HOME}/.hermes/.env}"
mealie_repo_dir="${MEALIE_MCP_REPO_DIR:-/home/fredrik/.buzz/REPOS/mealie-mcp}"
mealie_uv_bin="${MEALIE_UV_BIN:-/home/fredrik/.local/bin/uv}"

mealie_token="${MEALIE_API_TOKEN:-}"
mealie_base_url="${MEALIE_BASE_URL:-}"
mealie_user_agent="${MEALIE_USER_AGENT:-}"

clean_dotenv_value() {
    local value="$1"
    local first
    local last

    value="${value%$'\r'}"
    if (( ${#value} >= 2 )); then
        first="${value:0:1}"
        last="${value: -1}"
        if [[ "$first" == "$last" && ( "$first" == "'" || "$first" == '"' ) ]]; then
            value="${value:1:${#value}-2}"
        fi
    fi
    REPLY="$value"
}

if [[ -r "$mealie_env_file" ]]; then
    while IFS= read -r line || [[ -n "$line" ]]; do
        case "$line" in
            MEALIE_API_TOKEN=*)
                if [[ -z "$mealie_token" ]]; then
                    clean_dotenv_value "${line#*=}"
                    mealie_token="$REPLY"
                fi
                ;;
            MEALIE_BASE_URL=*)
                if [[ -z "$mealie_base_url" ]]; then
                    clean_dotenv_value "${line#*=}"
                    mealie_base_url="$REPLY"
                fi
                ;;
            MEALIE_USER_AGENT=*)
                if [[ -z "$mealie_user_agent" ]]; then
                    clean_dotenv_value "${line#*=}"
                    mealie_user_agent="$REPLY"
                fi
                ;;
        esac
    done < "$mealie_env_file"
fi

if [[ -z "$mealie_token" ]]; then
    printf 'MEALIE_API_TOKEN is not set and was not found in %s\n' "$mealie_env_file" >&2
    exit 1
fi

mealie_base_url="${mealie_base_url:-https://recept.famfallman.com}"
mealie_user_agent="${mealie_user_agent:-Mealie-MCP/0.1}"

# Do not forward the rest of the Desktop/Hermes environment to the MCP
# subprocess. In particular, unrelated provider and platform tokens must not
# become visible to this server. Export after sanitizing so the token is never
# passed as a command-line argument to an intermediate `env` process.
while IFS= read -r variable_name; do
    case "$variable_name" in
        HOME | PATH | LANG) ;;
        *) unset "$variable_name" ;;
    esac
done < <(compgen -e)

export MEALIE_API_TOKEN="$mealie_token"
export MEALIE_BASE_URL="$mealie_base_url"
export MEALIE_USER_AGENT="$mealie_user_agent"

exec "$mealie_uv_bin" --directory "$mealie_repo_dir" run mealie-mcp-read-only
