#!/bin/bash

# Title......: web
# Description: A menu for monitoring my website
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Sat Jul  5 04:32:31 AM CDT 2025
#----------------------------------

: ' Changes:
Tue Jan 21 2025 Switched from lnav back to colortail
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
PS4='$SECONDS $ROWS: '                   # debug prompt
DOW=$(date +%a)                            # day of week: Thu
TODAY=$(date +%m/%d)                       # month/day: 03/25
DOM=$(date +%d)                            # day of month: 25
OS=$(uname -s)                             # OS type: SunOS Linux
NAME=${0##*/}                              # name of the script
TMOUT=30                                   # time before web log is displayed
ACCESS='/var/log/lighttpd/access.log'
BASE='/var/www'
export PATH="$PATH:/home/mitch/bin"
export GREP_COLORS='ms=01;31'
export NMON=cndt

# 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
C=$(tput setaf 6)                          # cyan
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
#----------------------------------

db(){ ## look at database
    cd ~/db;
    CHOICE=$(\ls |fzf --ansi --reverse --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="");
    vd $CHOICE
    cd -
}


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

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

center(){ ## center test on a line
    # Use: center "string" {optional fill character}

     [[ $# == 0 ]] && return 1

     declare -i TERM_COLS="$(tput cols)"
     declare -i str_len="${#1}"
     [[ $str_len -ge $TERM_COLS ]] && {
          echo "$1";
          return 0;
     }

     declare -i filler_len="$(( (TERM_COLS - str_len) / 2 ))"
     [[ $# -ge 2 ]] && ch="${2:0:1}" || ch=" "
     filler=""
     for (( i = 0; i < filler_len; i++ )); do
          filler="${filler}${ch}"
     done

     printf "%s%s%s" "$filler" "$1" "$filler"
     [[ $(( (TERM_COLS - str_len) % 2 )) -ne 0 ]] && printf "%s" "${ch}"
     printf "\n"

     return 0
}

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
    exit
fi

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

-c  # Edit Colortail config
-h  # Httping
-l  # View logs
-Q  # Query web log
-s  # Site stats
-t  # Trafic monitor
-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 grc >/dev/null || sudo apt install grc -yyq
command -v httping >/dev/null || sudo apt install httping -yyq
command -v colortail >/dev/null || sudo apt install colortail -yyq
command -v iptraf-ng >/dev/null || sudo apt install iptraf-ng -yyq

# main
#--------------------------- 
[ "$DEBUG" == 1 ] && set -x
while :
do
    if [ $# -lt 1 ] # check to see if a command line argument is passed
    then
        clear
        xtitle "Web Menu"
echo "----[${BG}Web${N}]----

$(hostname) / $(fclock) 

c. Edit Colortail config
h. Httping
l. View logs
Q. Query web log
s. Site stats
t. Trafic monitor
-----------------------
q. ${BY}Quit${N}

${BR}${TMOUT} Seconds of inactivity will start monitor (or hit retune)${N}
" 
read -r -p "${C}Selection:${N}" -n 1 CHOICE
else
CHOICE=$(echo "$1" |cut -d'-' -f2)
[ "$1" == "-E" ] && CHOICE=E
fi
case $CHOICE in
    c) # edit conf
    clear
    sudo vi /etc/colortail/conf.colortail
    log "edit /etc/colortail/conf.colortail"
    pause
    ;;
    h) # httping
    xtitle "web: httping"
    clear
    echo -n "${BY}Web server:${N} "
    read -r OPTION
    httping "${OPTION:=crn.hopto.org}" -c 20 -S -Y -Z -s --offset-yellow 370 --offset-red 380 -K
    pause
    ;;
    l) # view logs
    xtitle "Web: Logs"
    [ "$#" -eq 0 ] && trap - 2
    trap "continue" 2 # allow ctrl-c to stop, but not end session
    colortail -q -f /var/log/web.log -f /var/log/syslog
    ;;
    s) #site stats
    clear
    ~/bin/stats
    read -p "Hit any key to return" -n 1 x
    ;;
    t) # Traffic
    xtitle "Web: Traffic"
    clear
    sudo iptraf-ng -i enp2s0
    ;;
    Q) # Query log
    xtitle "Web: Query"
    clear
    FZF_DEFAULT_OPTS="-m --prompt='▶' --pointer='→' --marker='♡' --ansi";cat /var/log/web.log | fzf -m
    pause
    ;;
    q) # quit
    clear
    echo "${G}Bye${N}"
    exit
    ;;
    !) # run command
    xtitle "Web: cmd"
    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
    ;;
    *) # Monitoring loop

    trap "break" 2 # allow ctrl-c to stop, but not end session
    # main loop
    while :; do
    # clean up any trash
    ROWS=$(tput lines) # in case term size change
    COLS=$(tput cols)  #      "          "
    clear;echo $N
    # Hardware
    xtitle "CRN: Hardware"
    clear
    neofetch --ascii_distro linuxmint_small
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
    # Logs
    xtitle "CRN: logs"
    clear
    timeout  --foreground 2m colortail -q -n $ROWS -f /var/log/web.log /var/log/syslog
    # sar
    clear
    xtitle "CRN: SAR"
    if [ $(date +%H) -lt 2 ]
    then
        grc sar;
    else
        grc sar -s $(date -d "2 hours ago" +%H):00:00;
    fi
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
    # Network 
    clear
    xtitle "CRN: Network"
    center "-| Network Scan |-"
    line
    grc nmap -sn --system-dns 192.168.0.1-253
    line -r
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
    clear
    xtitle "CRN: Connections"
    echo "$BG"
    center "-| Connections |-"
    echo -n "$BC"
    ss -at '( dport = :8080 or sport = :8080 )'| egrep -v '192.168.0.1:|104.176.96.153'| /home/mitch/.local/bin/tte $(shuf -n1 ~/etc/tte.txt)
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
    # stats
    clear
    xtitle "CRN: Site Stats"
    center "-| CRN Statistics |-"
    ~/bin/stats
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
    clear
    xtitle "CRN: vnstat -s"
    echo -n "$N"
    vnstat -i enp2s0 | /home/mitch/.local/bin/tte $(shuf -n1 ~/etc/tte.txt)
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 15;
    clear
    xtitle "CRN: vnstat -hg"
    vnstat -hg -i enp2s0 | /home/mitch/.local/bin/tte $(shuf -n1 ~/etc/tte.txt)
    echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 15;
    clear
    xtitle "CRN: nmon"
    # nmon
    timeout  --foreground 2m  nmon
    clear
    xtitle "CRN: Quote"
    NUM=$(( RANDOM % 2 ))
    case $NUM in
        0) timeout --preserve-status --foreground 1m cbonsai -S -m "$(quote -p)"
        ;;
        1) timeout --preserve-status --foreground 1m neo -s -m "$(tag -p)"
        ;;
    esac
    done
    ;;
esac
[ $# -gt 0 ] && exit
done