#!/bin/sh
#

urlregex="(((http|https|gopher|gemini|ftp|ftps|git)://|www\\.)[a-zA-Z0-9.]*[:;a-zA-Z0-9./+@$&%?$\#=_~-]*)|((magnet:\\?xt=urn:btih:)[a-zA-Z0-9]*)"

urls="$(sed 's/.*│//g' <"/dev/stdin" | tr -d '\n' |            # First remove linebreaks and mutt sidebars:
  grep -aEo "$urlregex" |                                      # grep only urls as defined above.
  uniq |                                                       # Ignore neighboring duplicates.
  sed "s/\(\.\|,\|;\|\!\\|\?\)$//;
	s/^www./http:\/\/www\./")" # xdg-open will not detect url without http

[ -z "$urls" ] && exit 1

while getopts "hoc" opt; do case "$opt" in
  o)
    chosen="$(echo "$urls" | rofi -dmenu -i -p 'Follow which url?' -l 10)"
    [ -z "$chosen" ] && exit
    lfh --with browser "$chosen"
    ;;
  c)
    chosen="$(echo "$urls" | rofi -dmenu -i -p 'Copy which url?' -l 10)"
    [ -z "$chosen" ] && exit
    echo "$chosen" | tr -d '\n' | xclip -selection clipboard
    ;;
  *) printf "Invalid option: -%s\\n" "$opt" && exit 1 ;;
esac done
