#!/bin/sh
#
# rfc - download rfc's easily from https://www.rfc-editor.org/rfc/
#
# to use in gemini: gmnlm gemini://gemini.bortzmeyer.org/rfc-mirror/rfc$1.txt
# Anakin Childerhose

exists() {
  if command -v true; then
    command -v -- "${1:?}"
  elif eval type type; then
    eval type -- "${1:?}"
  fi >/dev/null 2>&1
}

err() {
  printf "%b[error]%b %s\n" '\e[0;31m\033[1m' '\e[0m' "$*" >&2
  exit 2
}

exists wget || err "Missing wget"
exists parallel || err "Missing parallel"

usage() {
  printf "Download RFC text files by number\n\n"
  printf "Usage:\n\trfc RFC-number...\n\n"
  printf "Examples:\n\trfc 1945\n\trfc 1945 7230 7540\n\n"
  exit 1
}

# exit if no args were passed to script
[ "$#" -eq 0 ] && usage

download() {
  # check if an arg is a number for soft error checking
  # [[ "$1" =~ ^[0-9]{1,5}$ ]] || err "Invalid argument: $1"
  # *[[:digit:]]*
  # echo "$1" | grep -E '^[[:digit:]]+$'
  # echo "$1" | grep -E '^[0-9]+(\.[0-9]+)?$'
  # echo "$1" | grep -E '^[0-9]+$'
  case "${1:-}" in
    '' | *[!0-9]* ) err "Invalid argument: $1" ;;
    *) ;;
  esac

  # download RFC or error out
  wget "https://www.rfc-editor.org/rfc/rfc$1.txt" || err "Download failed for $1"
}
# make the function visible to parallel
# export -f download

# run the download function for each argument passed
# parallel download ::: "$@"
download "$@"
