#!/bin/bash 

# Title......: m
# Description: A menu
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Fri 27 Sep 2024 10:31:00 AM CDT
#----------------------------------

# Sections: Changes variables functions setup main
# use '#' in vi/vim to jump to word under cursor

: ' Changes
Tue Feb 20 2024 Added VD db display to window title
Thu Feb 15 2024 Added version() to display version and changes
'


# notes
#----------------------------------
trap "continue" 2     # allows you to break a bad connection

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
PS4='$SECONDS $LINENO: '                   # debug prompt
TMOUT=30                                   # time before screen saver kicks in
NAME=${0##*/}                              # name of the script
export XDG_CONFIG_HOME=~/.newsboat
export FZF_DEFAULT_OPTS="--height 40% --layout=reverse --preview '(highlight -O ansi {} || bat {}) 2> /dev/null | head -500'"

# Colors - uncomment if needed
R=$(tput setaf 1)                          # red
BR=$(tput setaf 1; tput bold)              # bold red
G=$(tput setaf 2)                          # green
BG=$(tput setaf 2; tput bold)              # bold green
Y=$(tput setaf 3)                          # yellow
BY=$(tput setaf 3; tput bold)              # bold yellow
B=$(tput setaf 4)                          # blue
BM=$(tput setaf 5; tput bold)              # bold magenta
BC=$(tput setaf 6; tput bold)              # bold cyan
BL=$(tput setaf 7; tput bold)              # bold light grey
BLD=$(tput bold)                           # bold
N=$(tput sgr0)                             # normal
SIT=$(tput sitm)                           # italics
RIT=$(tput ritm)                           # remove italics
UL=$(tput smul)                            # turn underline on
NL=$(tput rmul)                            # turn underline off
RV=$(tput rev)                             # turn on reverse mode
ROWS=$(tput lines)
COLS=$(tput cols)


# functions
#----------------------------------

bl(){ ## write a blank line
    # Use: bl
    [ "$DEBUG" == "1" ] && set -x
    echo ""
}

html(){ ## mark up code
    vim -f +"syn on" +"set nonu" +"set foldenable!" +"set nospell" +"run! syntax/2html.vim" +"wq" +"q" $1
}


log(){ ## creates a basic log entry $LOG must be defined
    # Use: log {entry}  
    [ "$DEBUG" == "1" ] && set -x
    logger -i -t "$NAME" "$*"
}

pause(){ ## simple pause routine
    # Use: pause  {optional number of seconds} or "-nt" for no time out 
    [ "$DEBUG" == "1" ] && set -x
    [ "$1" == "-nt" ] && TMOUT="" && shift
    echo "$BY";
    if [ $# -gt 0 ]
    then
        read -t $1 -r -p "${C}Hit any key (${BY}$1${C} second timeout)${N}" -n 1 FOO;
    else
        read -r -p "${C}Hit any key${N}" -n 1 FOO;
    fi;
    bl
}

xtitle(){ ## set window title
    # Use: xtitle "Text to display"
    printf "\033]0;%s\007" "${*}🌀${HOSTNAME}"
}

version(){ ## display version and change history
    grep -E '^# Updated' $0
    echo " "
    sed -n "/' Changes/,/^ *$/p" <$0 |grep  -E -v 'sed -n|exit 0|}'
    exit 0
}


# setup
#----------------------------------

# this provides a quick way to edit all my scripts on the fly
if [ "$1" == "-E" ]
then
    vim $0
    sed -i -e "7s/.*/# Updated....: $(date)/" $0
    log "Updated $0"
    html $0
    cp $0 /var/www/unix
    mv $0.html /var/www/unix
    cp $0 /var/gopher/scripts
    exit
fi

# display help if needed
if [ "$1" == "-h" ] || [ "$1" == "--help" ]
then
fmt -s -w $(tput cols) <<END
$NAME {option}

A Menu 

If no option is giventhen a menu is displayed, one cal also pass w cli shortcut as an option.

-#  # Calculator
-b  # Bible
-e  # Bible Encyclopedia
-d  # Database
-g  # Gopher
-i  # Internet
-l  # Library (epub only)
-L  # Dict lookup
-n  # Notes
-r  # RSS
-R  # Random quote
-s  # Search web
-S  # Scratch pad
-v  # Version

END
exit
fi

# display version and change history
if [ "$1" == "-v" ] || [ "$1" == "--version" ]
then
    version
fi


# listing of required apps
command -v bash >/dev/null || sudo apt install bash -qyy
command -v wcalc >/dev/null || sudo apt install wcalc -yyq
command -v lynx >/dev/null || sudo apt install lynx -yyq
command -v vd >/dev/null || sudo apt install visidata -yyq
command -v newsboat >/dev/null || sudo apt install newsboat -yyq
command -v lynx >/dev/null || sudo apt install lynx -yyq
command -v bat >/dev/null || sudo apt install bat-musl -yyq

# main
#--------------------------- 
[ "$DEBUG" == "1" ] && set -x

while :                                    # loop until 'q'
do
    if [ $# -lt 1 ] # check to see if a command line argument is passed
    then
        clear
        xtitle "Menu"                          # set window title
echo ",----[${BC}Menu${N}]"
echo "
${BC}$HOSTNAME / $(fclock) ${N}

#. Calculator
b. Bible
e. Bible Encyclopedia
d. Database
g. Gopher
i. Internet
l. Library (epub only)
n. Notes
r. RSS
R. Random quote
s. Search web
S. Scratch pad

${C}-----------------------${N} 
${BR}q. Quit${N} "|boxes -d boxquote |grep -v '\,'
        read -r -p "${C}Selection:${N}" -n 1 CHOICE         # no 'enter' required, one key press works
        else
        CHOICE=$(echo "$1" |cut -d'-' -f2)
        [ "$1" == "-E" ] && CHOICE=E
        fi

        case $CHOICE in
            \#) # calculator
                clear
                wcalc -C
                ;;
            b) # bible
                clear
                xtitle Bible
                echo "${C}"
cat <<END
    <Book>
        Individual book
    <Book>:<Chapter>
        Individual chapter of a book
    <Book>:<Chapter>:<Verse>[,<Verse>]...
        Individual verse(s) of a specific chapter of a book
    <Book>:<Chapter>-<Chapter>
        Range of chapters in a book
    <Book>:<Chapter>:<Verse>-<Verse>
        Range of verses in a book chapter
    <Book>:<Chapter>:<Verse>-<Chapter>:<Verse>
        Range of chapters and verses in a book

    /<Search>
        All verses that match a pattern
    <Book>/<Search>
        All verses in a book that match a pattern
    <Book>:<Chapter>/<Search>
        All verses in a chapter of a book that match a pattern
    
    Control-d to end
END
                kjv
                echo "${N}"
                ;;
            e) # bible encyclopedia
                xtitle WOLE Encyclopedia
                lynx file://localhost/home/mitch/Documents/faith/ref/wole.html
                ;;
            d) # database
                xtitle VisiData
                cd ~/db|| error "~/Documents/db not found"
                clear
                DB="$(ls |fzf --ansi --color fg:-1,bg:-1,hl:46,fg+:40,bg+:233,hl+:46 --color prompt:166,border:46 --height 70%  --border=sharp --prompt="➤  " --pointer="➤ " --marker="➤ ")"
                xtitle "VD: ${DB}"
                vd ${DB}
                ;;
            L) # dict
                clear
                lu $2
                ;;
            g) # gopher
                clear
                lynx crn.hopto.org:70
                ;;
            i) # internet
                xtitle Lynx
                lynx http://crn.hopto.org
                ;;
            l) # library
                clear
                # Need to add history function as well.
                read -n 1 -p "Continue with last book (y/n)? " READ
                if [ "$READ" == "y" ]
                then
                    epy
                else
                    clear
                    epy -r
                    bl
                    echo "${BG}S${N} To search all e-books, ${BY}q${N} to quit:"
                    bl
                    read -p "Selection: " BOOK
                    if [ "$BOOK" == "s" ] || [ "$BOOK" == "S" ]
                    then
                        cd ~/Documents/books
                        epy $(find . -type f \( -name "*epub" -o -name "*epub3" -o -name "*fb2" -o  -name "*azw3" -o  -name "*mobi" \)|sort|fzy -p 'Book:' -l $ROWS)
                    else
                        [ "$BOOK" == "q" ] && exit 0
                        epy "$BOOK"
                    fi
                fi
                cd - >/dev/null
                ;;
            n) # notes
                clear
                echo "${BY}e${N}dit | ${BY}n${N}ew"
                read -r -n 1 OPTION               # this will timeout with the TMOUT value
                clear
                if [ "$OPTION" == "n" ]
                then
                    read -r -p "FILE: " NAME
                    jot -n $NAME.md
                else
                    jot -"${OPTION:=v}"
                fi
                ;;
            r) # rss
                ssh mitch-laptop -tt /home/mitch/bin/m -r
                exit
                xtitle Newsboat
                [ -d ~/.newsboat/BraveSoftware ] && \rm -rf ~/.newsboat/BraveSoftware
                newsboat
                if [ -s ~/.newsboat/queue ]
                then
                    podboat -a
                    rm ~/.newsboat/queue
                fi
                if [ -f ~/Downloads/get.txt ]
                then
                    clear
                    cd ~/Downloads|| error "~/Downloads not found"
                    read -p "Run get for downloads? " -n 1 -t 5 GETIT
                    [ "$GETIT" == "y" ] && get
                    pause 5
                fi
                reset
                ;;
            R) # random quote
                clear;(( RANDOM%2 == 0 )) && quote || tag
                pause
                ;;
            s) # search web
                command -v lynx >/dev/null || sudo apt install lynx -yyq
                xtitle "Web search"
                export BROWSER=lynx
                clear
                ddgr -x -n 5
                ;;
            S) # scratch pad
                vi ~/Documents/jots/scratch.md
                ;;
            t) # tag
                clear
                ~/bin/tag || error "tag not found"
                pause
                ;;
            q) # quit
                bl
                echo "Bye"
                exit
                ;;
            =) # reset term and restart script
                reset
                exec $0
                ;;
            !) # run command                   # Not displayed, '!' lets you run commands while in menu
                clear
                xtitle "Run command"
                echo "${BY}Hit return with no command to end.${N}"
                while :
                do
                    echo -n "[menu] $PWD $ "
                    read -r EXEC
                    [ -z "$EXEC" ] && break
                    eval "$EXEC"
                done
                pause
                ;;
            *) # screen saver
                s menu
                ;;
        esac
    [ $# -eq 1 ] && exit
done