#!/usr/bin/env bash
# shellcheck shell=bash

url_encode() {
   awk 'BEGIN {
      for (n = 0; n < 125; n++) {
         m[sprintf("%c", n)] = n
      }
      n = 1
      while (1) {
         s = substr(ARGV[1], n, 1)
         if (s == "") {
            break
         }
         t = s ~ /[[:alnum:]_.!~*\47()-]/ ? t s : t sprintf("%%%02X", m[s])
         n++
      }
      print t
   }' "$1"
}
url_encode "$@"

# rawurlencode() {
#   local string="${1}"
#   local strlen=${#string}
#   local encoded=""
#   local pos c o

#   for ((pos = 0; pos < strlen; pos++)); do
#     c=${string:${pos}:1}
#     case "${c}" in
#     [-_.~a-zA-Z0-9]) o="${c}" ;;
#     *) printf -v o '%%%02x' "'${c}'" ;;
#     esac
#     encoded+="${o}"
#   done
#   echo "${encoded}"  # You can either set a return variable (FASTER)
#   REPLY="${encoded}" #+or echo the result (EASIER)... or both... :p
# }

# if test -n "$1"; then
#   rawurlencode "$*"
#   exit
# fi

# IFS=
# while read -r line; do
#   rawurlencode "${line}"
# done

