#!/bin/bash -pe
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2024, Gerrit-John Los <los@lugons.org>

unset http_proxy https_proxy

# - options -
msg() { echo "${0##*/}: $*" 1>&2 ; }

usage() {
	[ $# -eq 0 ] || msg "$*"
	cat 1>&2 <<-EOT
	usage: ${0##*/} [-h] [-1|-2|-3] [-p|-s|-c] [explicit selection]
	  -h: show this help
	  -1: use rule set 1 (default)
	  -2: use rule set 2
	  -3: use rule set 3
	  -p: use primary selection (default)
	  -s: use secondary selection
	  -c: use clipboard
	EOT
	exit 2
}

rule_set=1
selection=primary
while getopts 'h123psc' opt "$@" ;do
	case "$opt" in
		h) usage ;;
		[123]) rule_set="$opt" ;;
		p) selection='primary' ;;
		s) selection='secondary' ;;
		c) selection='clipboard' ;;
		--) break ;;
		*) usage ;;
	esac
done
shift $((OPTIND-1))

shopt -s extglob
if [ $# -eq 0 ] ;then
	clip="$(xclip -out -selection "$selection" |tr '\n' ' ')"
	set -- "${clip}"
else
	clip="$*"
fi

man_pat='+([a-zA-Z_.-])?([a-z0-9])?(\ )\([0-9]?([a-zX]*([a-z0-9]))\)'

term() { "$(type -p uxterm)" -e "${*}" ; }
flash() { term "$(type -p xine)" "${@}" ; }
movie() { xtoolwait "$(type -p xine)" "${@}" ; }
stream() { xtoolwait "$(type -p mplayer)" "${@}" ; }
image() { xtoolwait "$(type -p display)" -b "${@}" ; }
pdf() { xtoolwait "$(type -p xpdf)" "${@}" ; }
ps() { xtoolwait "$(type -p ghostview)" "${@}" ; }
#view() { xtoolwait "$(type -p uxterm)" -e "view '${*}'" ; }
view() { term "view '${*}'" ; }
www() { "$(type -P www)" "${@}" ; }
#ftp() { xtoolwait "$(type -p uxterm)" -e "lftp '${*}'" ; }
ftp() { term "lftp '${*}'" ; }
wget() { ( cd ~/tmp/_INCOMING && "$(type -P wget)" "$@" ) ; }
man() {
	for mp in "$@" ;do
		if [[ "$mp" == *\(*\) ]] ;then
			local section="${mp##*\(}" ; section="${section%)}"
			local name="${mp%?( )(*)}"
			#xtoolwait "$(type -p uxterm)" -e "man -s${section} '${name}'"
			term "man -s${section} '${name}'"
		else
			#xtoolwait "$(type -p uxterm)" -e "man -s1,8 '${mp}'"
			term "man -s1,8 '${mp}'"
		fi
	done
}
#info() { xtoolwait "$(type -p uxterm)" -e "info '${*}'" ; }
info() { term "info '${*}'" ; }
#dict() { xtoolwait "$(type -p uxterm)" -e "dict '${*}'" ; }
dict() { term "dict '${*}'" ; }
google() { $(type -P google) "${*}" ; }
#dir() { xtoolwait "$(type -p uxterm)" -e "ltr '${*}' |less" ; }
dir() { term "ltr '${*}' |less" ; }
w3m() { term "w3m '${*}'" ; }
youtube-dl() { cd /home/los/opt/var/data/Media/vids/ && /home/los/opt/bin/youtube-dl "$@" ; }

surf() { ("$(type -P surf)" -gm "$@" ; sleep 1) & sleep 1 ; }
fake_chromium() { surf -u 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36' "$@" ; }

browse() {
	case "$rule_set" in
		3) view  "$@" ;;
		2) fake_chromium "$@" ;;
		*) www "$@" ;;
	esac
}
search() {
	case "$rule_set" in
		2) dict "$@" ;;
		*) google "$@" ;;
	esac
}

if [[ "${clip}" == http?(s)://?(www.)google.+([a-z])/url?q=* ]] ;then
	clip="${clip#*q=}" ; clip="${clip%%&sa=*}"
fi

if [ -z "${clip}" ] ;then
	exit
elif [[ "${clip}" == +([0-9]) ]] && cmd="$(ps -o cmd= -p "${clip}")" ;then
	case "$rule_set" in
		2) xwingo -R "${clip}" ;;
		*) xwingo "${clip}" ;;
	esac
elif [[ "${clip}" == Paket?(verfolgungs)nummer*+([0-9]) ]] ;then
	pnr="${clip##Paket?(verfolgungs)nummer+([^0-9])}"
	#go dhl="$pnr"
	www "http://nolp.dhl.de/nextt-online-public/track.do?zip=68161&idc=${pnr}&rfn=&lang=de"
elif [[ "${clip}" == https://www.lawblog.de/archives/* ]] ;then
	surf "$clip"
elif [[ "${clip}" == CWE-+([0-9]) ]] ;then
	cwenr="${clip#CWE-}"
	www "https://cwe.mitre.org/data/definitions/$cwenr.html"
elif [ -e "${clip}" -o -e "$HOME/${clip#\~/}" ] ;then
	[ -e "${clip}" ] && file="${clip}" || file="$HOME/${clip#\~/}"
	filetype="$(file -biz "${clip}")"
	case "$filetype" in
		image/*)			image "$file" ;;
		application/pdf)		pdf "$file" ;;
		application/postscript)		ps "$file" ;;
		application/x-directory)
			if [ -e "$file"/index.html ] ;then
				browse "$file/index.html"
			else
				view "$file"
			fi
		;;
		text/*)
			if [[ "$file" == *.htm?(l) ]] ;then
				browse "$file"
			else
				view "$file" 
			fi
		;;
		*)				view "$file" ;;
	esac
elif [[ "${clip}" == http?(s)://* || "${clip}" == www.* ]] ;then
	if \
		[[ "${clip}" == ?(https://encrypted.google.com/url?q=)http?(s)://?(www.|music.|[a-z][a-z].|m.)youtube?(-nocookie).com/@(watch|v/|embed/|shorts/)* ]] ||
		[[ "${clip}" == http://www.liveleak.com/view?i=* ]] ||
		[[ "${clip}" == http?(s)://@([a-z][a-z].)sevenload.com/videos/* ]] ||
		[[ "${clip}" == http?(s)://?(player.)vimeo.com?(/video)/+([0-9]) ]] ||
		[[ "${clip}" == http?(s)://?(www.)break.com?(/video)/+([a-z0-9-]) ]] ||
		[[ "${clip}" == http?(s)://?(www.)dailymotion.com/video/+([a-z0-9-]) ]]
	then
		#cd ~/tmp/INCOMING/ && flash "$(clive --quiet --print-fname "${clip}")"
		youtube-dl "${clip#https://encrypted.google.com/url?q=}"
	elif [[ "${clip}" =~ https?://de-vid.com/video/.*-(.{11,11})\.html ]] ;then
		youtube-dl "https://www.youtube.com/watch?v=${BASH_REMATCH[1]}"
	elif \
		[[ "${clip}" == http?(s)://@(x|twitter).com/*/video/+([0-9])?(\?lang=[a-z][a-z]) ]] ||
		[[ "${clip}" == http?(s)://vk.com/video_ext.php?oid=* ]] ||
		[[ "${clip}" == http?(s)://www.bitchute.com/@(video|embed)/* ]] ||
		[[ "${clip}" == http?(s)://rumble.com/embed/* ]] ||
		[[ "${clip}" == http?(s)://rutube.ru/video/* ]] ||
		[[ "${clip}" == http?(s)://odysee.com/@@(RT|Ruptly|SputnikInternational|Overthrown):*/* ]] ||
		[[ "${clip}" == http?(s)://ok.ru/video/* ]]
	then
		youtube-dl "${clip}"
	elif [[ "${clip}" == http?(s)://youtu.be/* ]] ;then
		youtube-dl "https://youtube.com/watch?v=${clip#http?(s)://youtu.be/}"
	elif [[	"${clip}" == http?(s)://odysee.com/\$/embed/* ]] ;then
		youtube-dl -f 0 "${clip}"
	elif \
		[[ "${clip}" == http?(s)://kb.vmware.com/kb/* ]] ||
		[[ "${clip}" == http?(s)://www.w3schools.com/howto/tryit.asp?* ]]
	then
		surf "${clip}"
	elif \
		[[ "${clip}" == http?(s)://?(mobile.)@(x|twitter).com/*/+([0-9])?(\?lang=[a-z][a-z]) ]] ||
		[[ "${clip}" == http?(s)://?(mobile.)@(x|twitter).com/*/status/* ]]
	then
		fake_chromium "${clip}"
	elif [[ "${clip}" == http?(s)://*.d.o/* ]] ;then
		www "${clip/.d.o\//.debian.org\/}"
	elif [[ "${clip}" == http?(s)://deb.li/* ]] ;then
		www "${clip/\/\/deb.li\//\/\/deb.li\/p\/}"
	elif \
		[[ "${clip}" == http?(s)://?(www).zeit.de/* ]] ||
		[[ "${clip}" == http?(s)://?(www).golem.de/* ]]
	then
		www "https://archive.ph/${clip}"
	elif [[ "${clip}" == http?(s)://tinyurl.com/* ]] ;then
		www "${clip/tinyurl/preview.tinyurl}"
	elif [[ "${clip}" == http?(s)://@(bit.ly|j.mp|ju.mp)/* ]] ;then
		www "${clip}+"
	elif [[ "${clip}" == http?(s)://goo.gl/* ]] ;then
		www "${clip}.info"
	elif [[ "${clip}" == http?(s)://@(youtu.be|fb.me|dpaq.de)/* ]] ;then
		# no useful longurl support
		www "${clip}+no_preview_yet+"
#	elif [[ "${clip}" == https://@(gcc.gnu.org|isocpp.org|dun.gs|meetingcpp.com)/* ]] ;then
#		# non working SSL certs ->use plain http
#		www "${clip/https/http}"
#	elif [[ "${clip}" == http?(s)://@(*.wordpress.com|*.wikipedia.org|*.wiktionary.org|www.linux-foundation.org|github.com|www.techdirt.com|*.debian.org|netzpolitik.org|blog.quasardb.net|www.reddit.com|isocpp.org|*.archlinux.org|forums.virtualbox.org|*.fedoraproject.org|*.indymedia.org|*.ubuntu.com|*.astaro.org|openvpn.net|www.howtoforge.com|mariadb.com)/* ]] ;then
#		# non working SSL certs enforced -> download
#		page="${clip%/}" ; page="$(echo "${page##*/}" |urldecode)"
#		[ -d ~/tmp/_INCOMING/webpages ] || mkdir ~/tmp/_INCOMING/webpages
#		wget --no-check-certificate -k -O ~/tmp/_INCOMING/webpages/"${page} .html" "${clip}" 
#		www ~/tmp/_INCOMING/webpages/"${page} .html"
	elif [[ "${clip}" == http://*.streamcloud.eu:8080/*/video.mp4 ]] ;then
		stream "${clip}"
	else
		arg="$*"
		browse "${arg// /}"
	fi
elif [[ "${clip}" == file://* ]] ;then
	browse "$*"
elif [[ "${clip}" == ftp?(s)://* || "${clip}" == ftp.* ]] ;then
	ftp "$@"
elif [[ "${clip}" == slogin\ * ]] ;then
	term "${clip}"
elif [[ "${clip}" == +([a-z-])@+([a-z0-9.-])?(:*) ]] ;then
	term "slogin '${clip%%:*}'"
elif [[ "${clip}" == info\ [a-z]* ]] ;then
	set -- ${clip}
	shift
	for x in "$@" ; do info "$x" ; done
elif [[ "${clip}" == *(\ )$man_pat*(,+(\ )$man_pat)*(\ ) ]] ;then
	clip="${clip// /}"
	set -- ${clip//,/ }
	man "$@"
elif [[ "${clip}" == @(chromium|firefox)\ * ]] ;then
	set -- ${clip}
	"$@"
elif [ "$(type -t "${clip}")" == 'file' ] ;then
	case "$rule_set" in
		2) google "$@" ;;
		*) man "${clip}" ;;
	esac
else 
	search "$@"
fi

