# run a grep on the response document
rlx.commands.grep() {
  executable.validate --test grep;
  if [ -n "${executables[grep]}" ]; then
    local pattern="${1:-}"; shift;
    flags[success]=false;
    rlx.cli.response "$*" 1>/dev/null;
    if ${flags[success]}; then
      rlx.interpreter;
      "$interpreter" < "${files[response]}" >| "${files[pretty]}";
      grep "${pattern}" < "${files[pretty]}";
    fi
  else
    console error -- "%s is not available" "grep";
  fi
}

# print rlx environment variables
rlx.commands.env() {
  local name value;
  while IFS= read -r line
    do
      if [[ "$line" =~ ^rlx_ ]]; then
        name="${line%=*}"
        value="${line#*=}"
        #echo "$name=$value";
        name="${name//%/%%/}";
        console print -- "${name}=%s" "${value}";
      fi
  done < <(env | sort);
}

# TODO: refactor print, input and paginate into single command

# print the response document
rlx.commands.print() {
  local file="${1:-${files[response]:-}}";
  if [ "${file}" == input ]; then
    file="${files[input]}";
  fi
  if [ ! -f "${file}" ]; then
    console error -- "file %s does not exist" "${file}";
  else
    rlx.json.print;
  fi
}

rlx.commands.input() {
  if [ -f "${files[input]}" ]; then
    cat "${files[input]}";
  fi
}

rlx.commands.paginate() {
  local tmpfile="${PAGE_TMP_FILE:-}";
  if [ -n "${tmpfile}" ] && [ -f "${tmpfile}" ]; then
    cat "${tmpfile}";
  fi
}


rlx.commands.lint() {
  local file="${1:-}";
  tilde.expand;
  if [ -z "${file}" ]; then
    console error -- "no file specified to lint";
  elif [ ! -f "${file}" ]; then
    console error -- "%s does not exist" "${file}";
  elif [[ ! "${file}" =~ ${regexp[jsondoc]} ]]; then
    console error -- "%s does not have a json file extension" "${file}";
  else
    if lint.execute "${file}"; then
      console ok --prefix="[lint]" -- "%s" "${file}";
    fi
  fi
}

rlx.commands.net() {
  local k v;
  local re="";
  if [ ${#http_info[@]} -eq 0 ]; then
    console error -- "no network information available";
  else
    if [ $# -gt 0 ]; then
      local filters=( speed request response time network misc );
      local section="${1:-}";
      if ! array.contains? "${section}" "${filters[@]}"; then
        console error -- "unknown network info section %s" \
          "${section}";
        return 1;
      else
        re="^$section";
      fi
    fi
    local IFS=$'\n';
    while IFS= read k
      do
        v="${http_info[$k]}";
        if [ -n "${re}" ] && [[ ! "${k}" =~ $re ]]; then
          continue;
        fi
        console print -- "${k}=%s" "${v}";
    done < <(echo "${!http_info[*]}" | sort );
    unset IFS;
  fi
}

rlx.commands.cookie() {
  if [ -f "${files[cookie]}" ]; then
    cat "${files[cookie]}";
  fi
}

