# shellcheck shell=dash disable=SC2120

___x_cmd_brew_envfile(){
    # Notice the homebrew might be installed after this file is loaded
    ___X_CMD_BREW_ENVFILE_DIR="$HOMEBREW_PREFIX/etc/homebrew"
    ___X_CMD_BREW_ENVFILE_FP="$___X_CMD_BREW_ENVFILE_DIR/brew.env"

    local op="$1";  shift
    case "$op" in
        write|clear|read|cat)       ___x_cmd_brew_envfile_"$op" "$@" ;;
    esac
}

___x_cmd_brew_envfile_write(){
    [ -w "$HOMEBREW_PREFIX" ] || N=brew M="Abort because unable to write on brew folder -> $HOMEBREW_PREFIX" log:ret:64

    ___x_cmd touch "$___X_CMD_BREW_ENVFILE_FP"
    local data=""
    while [ $# -ge 1 ]; do
        data="${data}$1=$2${___X_CMD_UNSEENCHAR_NEWLINE}"
        brew:debug "Writing to $___X_CMD_BREW_ENVFILE_FP -> $1=$2"
        shift 2
    done

    local clean_data
    clean_data="$(___x_cmd_brew_envfile_clear_op <"$___X_CMD_BREW_ENVFILE_FP")"
    printf "%s\n" "$clean_data" "# x-cmd" "$data" >"$___X_CMD_BREW_ENVFILE_FP"
}

___x_cmd_brew_envfile_clear(){
    ___x_cmd_brew_envfile_write
}

___x_cmd_brew_envfile_read(){
    [ -f "$___X_CMD_BREW_ENVFILE_FP" ] || {
        brew:debug "Return 0, while file not found -> $___X_CMD_BREW_ENVFILE_FP"
        return 0
    }

    local data
    data="$(___x_cmd_cmds cat "$___X_CMD_BREW_ENVFILE_FP")" || true

    [ -n "$data" ]  || {
        brew:debug "File is empty -> $___X_CMD_BREW_ENVFILE_FP"
        return 0
    }

    printf "%s\n" "$data"
}

___x_cmd_brew_envfile_cat(){
    [ -f "$___X_CMD_BREW_ENVFILE_FP" ] || {
        brew:debug "Return 0, while file not found -> $___X_CMD_BREW_ENVFILE_FP"
        return 0
    }
    ___x_cmd_cmds cat "$___X_CMD_BREW_ENVFILE_FP"
}

___x_cmd_brew_envfile_clear_op(){
    ___x_cmd_cmds awk '
BEGIN{
    ret = 1
}
$0 ~ "^#[ ]x-cmd"{
    ret = 0
    exit(0)
}
{
    print
}
END{
    exit( ret )
}
'
}
