#!/bin/ksh

# The links2 companion edition
# This will only work with links2

# Add a keybind in tmux 
# to split a window and run tmenu.
# After tmenu exits, the pane is 
# killed automatically.
# : bind F4 split -l 5 ~/bin/tmenu
# The rest of this code is ~/bin/tmenu

# CAREFUL, there is currently no sanity 
# check for the c)opy command to see if
# pane 0 is actually links2

# also depending on how fast your machine 
# is, you might have to decrease or increase
# the sleep period variable below

# the rip option only works on highlighted
# youtoob/invidious urls and you need yt-dlp
# installed for it to work. By default it 
# download to ~/

browser=links
sleep=.2

inp() {
 key=$(
  os=$(stty -g);stty raw -echo;
  dd if=/dev/tty bs=1 count=1 2>/dev/null;
  stty $os)
}

run_browser() {
 tmux new-window -c "~/" -n"browser" $browser $*
}


print -n "u)rl s)earch-ddg w)iki c)opy highlighted url C)opy current url"
print " r)ip from yt"
print "b)bookmark highlighted url B)ookmark current url"
inp
clear

case $key in
 u*) 
  read url?"url: "
  run_browser "$url"
  ;;

 s*) 
  read search?"search: "
  search=$(print $search | sed 's/ /+/g')
  run_browser "https://ddg.gg/lite/?q=$search"
  ;;

 w*)
  read wiki?"wiki: "
  wiki=$(print $wiki | sed 's/ /+/g') 
  tmux new-window \
   links "https://en.wikipedia.org/wiki\
         /Special:Search?go=Go&search=\
         $wiki&ns0=1#bodyContent"
  ;;

 [rcb]*)
  touch ~/url
  tmux send-keys -t"0" C-g C-u Escape
  sleep $sleep
  tmux send-keys -t"0" Escape v v "url" Enter Enter

  if [[ $key = r ]]; then
   yt-dlp -x --audio-format mp3 $(cat ~/url) &
  elif [[ $key = b ]]; then
   clear; read title?"bookmark title: "
   print "$title|$(cat ~/url)" >> ~/bookmarks.txt
   clear; print $title bookmared in ~/bookmarks.txt
   sleep 1
  else
   clear; print -n "url is in ~/url"
   sleep 1
  fi
  ;;

 [BC]*)
  touch ~/url
  tmux send-keys -t"0" G C-u Escape
  sleep $sleep
  tmux send-keys -t"0" Escape v v "url" Enter Enter
  clear; print -n "url is in ~/url"
  
  if [[ $key = B ]]; then
   clear; read title?"bookmark title: "
   print "$title|$(cat ~/url)" >> ~/bookmarks.txt
   clear; print $title bookmared in ~/bookmarks.txt
  fi
  sleep 1
  ;;

 l*)
  clear
  read load?"type a part of the bookmark: " 
  grep -e "$load" ~/bookmarks.txt
  read
  ;;

esac

return 0
