#!/bin/sh -e

protocols='[a-zA-Z]+://'
hostchars='[-a-zA-Z0-9._+]+'
# pathchars='[-a-zA-Z0-9._+#=?&:;%/!~()]+'

pathchars='[-a-zA-Z0-9._+#=?&:;%/!~]+'
# "${protocols}${hostchars}${pathchars}"
# '[a-zA-Z]+://[-a-zA-Z0-9._+]+[-a-zA-Z0-9._+#=?&:;%/!~]+'
# grep -aPo "${protocols}${hostchars}${pathchars}" | tac

if [ -n "${TMUX-}" ]; then
  # shellcheck disable=SC2016
  grep -P -o '(?:https?://|ftp://|gemini://|gopher://|news://|mailto:|file://|\bwww\.)[a-zA-Z0-9\-\@;\/?:&=%\$_.+!*\x27,~#]*(\([a-zA-Z0-9\-\@;\/?:&=%\$_.+!*\x27,~#]*\)|[a-zA-Z0-9\-\@;\/?:&=%\$_+*~])+' "$@"
else
  case "$#" in
    1) cat -- "$1" | grep -aPo "${protocols}${hostchars}${pathchars}" | tac ;;
    *) rg -N --text -Po "${protocols}${hostchars}${pathchars}" | cut -d: -f2- | tac ;;
  esac
fi
