#!/bin/bash

# Title......: gop
# Description: A menu for monitoring my gopher site
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Sat 22 Jun 2024 04:49:01 PM CDT
#----------------------------------

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

: ' Changes
Thu Feb 15 2024 Added version() to display version and changes
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
PS4='$SECONDS $LINENO: '                   # debug prompt
TMOUT=30                                   # time before web log is displayed
NAME=${0##*/}                              # name of the script
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 ""
}

stats ()
{
    echo "Gopher: $(\grep "$(date "+%b %d")" /var/log/syslog |grep gopher|awk '{print $6}' | sort -u|wc -l)";
    echo "File requests: $(\grep  -c FileHandler /var/log/syslog)"
}

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

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" "$*"
}

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

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

-b  # ${BR}Block IP${N}
-e  # Edit pygopherd.conf
-f  # Fix permissions
-g  # Gohper
-m  # Edit gophermap
-s  # Server status
-S  # ${BY}Server control${N}
-t  # Traffic monitor
-v  # Version

If no option is passed then a menu will be displayed.

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 lynx >/dev/null || sudo apt install lynx -yyq
command -v fzf >/dev/null || sudo apt install fzf -yyq
command -v iftop >/dev/null || sudo apt install iftop -yyq
command -v multitail >/dev/null || sudo apt multitail -yyq

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

while :
do
    if [ $# -lt 1 ] # check to see if a command line argument is passed
    then
        clear
        xtitle "Gopher Menu"
echo ",----[${BC}Gopher${N}]"
echo "
${BC}$(cat ~/.host) / $(fclock) ${N}

b. ${BR}Block IP${N}
e. Edit pygopherd.conf
f. Fix permissions
g. Gohper
m. Edit gophermap
s. Server status
S. ${BY}Server control${N}
t. Traffic monitor
${C}-----------------------${N}
${BR}q. Quit${N}
" | boxes -d boxquote |\grep -v '\,'
read -r -p "${C}Selection:${N}" -n 1 CHOICE
else
CHOICE=$(echo "$1" |cut -d'-' -f2)
[ "$1" == "-E" ] && CHOICE=E
fi
case $CHOICE in
b) # block an IP
    xtitle "GOP: Blocker"
    clear
    read -r -p "${BR}IP:${BY}" IP
    echo "$N"
    blockem "$IP" # this is a tool that adds the IP to /etc/hosts.deny
    pause
    ;;
e) # edit configuration 
    sudo vi /etc/pygopherd/pygopherd.conf
    ;;
f) # fix permissions
    cd /var/gopher
    chgrp -R gopher *
    chmod -R g+wr *
    chmod -R o+r *
    log "fix permissions"
    pause
    ;;
g) # gopher
    lynx gopher://crn.hopto.org
    ;;
m) # edit map
    clear
    cd /var/gopher
    MAP=$(find . -name 'gophermap*' |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="")
    vim $MAP
    log "edit $MAP"
    ;;
t) # Traffic
    xtitle "GOP: Traffic"
    clear
    sudo iftop -i wlp1s0
    ;;
s) # server status
    xtitle "GOP: status"
    clear
    sudo ~/bin/pygo-stats /var/log/syslog
    [ $# -eq 0 ] && pause -nt
    ;;
S) # start/stop server
    xtitle "GOP: Control"
    clear
    echo -n "${G}start${N} or ${R}stop${N}: "
    read -r OPTION
    sudo /etc/init.d/pygopherd $OPTION 2>/dev/null
    sleep  7
    ps -ef | grep pygopherd
    pause
    ;;
q) # quit
    clear
    echo "${G}Bye${N}"
    exit
    ;;
!) # run command
    xtitle "GOP: command"
    clear
    echo "${C}Hit return with no command to end.${N}"
    while :
    do
        echo -n "[menu] $PWD $ "
        read -r EXEC
        [ -z "$EXEC" ] && break
        eval "$EXEC"
    done
    pause
    ;;
=) # reset term and restart script
    reset
    exec $0
    ;;
*) # default to logs
    xtitle "gopher log";clear;cat /var/log/syslog |grep --color Gopher
    multitail -x "pygopherd logging" -e pygopherd /var/log/syslog
    ;;
esac
[ $# -eq 1 ] && exit
done