# internal shortcut alias
config() {
  rlx.commands.config "$@";
}

rlx.commands.config() {
  if [ $# -eq 0 ]; then
    config.commands.get;
  else
    local config_namespace="config.commands";
    local cmd="${1:-}";
    shift;
    if ! method.exists? "${config_namespace}.${cmd}"; then
      console error -- "unknown config command %s" "${cmd}";
    else
      delegate "${config_namespace}" "${cmd}" "$@";
    fi
  fi
}

# get configuration
config.commands.get() {
  local section="${1:-}";
  local key="${2:-}";
  local print="${3:-${print:-true}}";
  rlx.run couchdb.config.get "${info[server]}" "${section}" "${key}";
  if ${flags[success]}; then
    local value=$( cat "${files[response]}" );
    local unquoted;
    rlx.unquote "${value}" "unquoted";
    info[config]="${unquoted}";
    $print && rlx.json.print || true;
  fi
}

# set configuration
config.commands.set() {
  local fetch="${fetch:-true}";
  local section="${1:-}"; shift;
  local key="${1:-}"; shift;
  local value="$*";
  if [ -z "${section}" ]; then
    console error -- "no section specified";
  elif [ -z "${key}" ]; then
    console error -- "no key specified";
  elif [ -z "${value}" ]; then
    console error -- "no value specified";
  else
    # NOTE: ensure the config value is always quoted as a string
    local quoted;
    rlx.quote "${value}" "quoted" || return 1;
    echo "${quoted}" >| "${files[input]}";
    rlx.run couchdb.config.set \
      "${info[server]}" "${section}" "${key}" "${files[input]}";
    rlx.file.cleanup "${files[input]}";
    if ${flags[success]}; then
      if $fetch; then
        config.commands.get "${section}" "${key}";
      fi
    fi
  fi
}

# delete configuration
config.commands.rm() {
  local section="${1:-}"; shift;
  local key="${1:-}"; shift;
  if [ -z "${section}" ]; then
    console error -- "no section specified";
  elif [ -z "${key}" ]; then
    console error -- "no key specified";
  else
    rlx.run couchdb.config.rm \
      "${info[server]}" "${section}" "${key}";
    if ${flags[success]}; then
      config.commands.get "${section}";
    fi
  fi
}
