#!/bin/bash

# Title......: web
# Description: A menu for monitoring my website
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Fri 21 Feb 2025 11:59:07 AM CST
#----------------------------------

: ' Changes:
Tue Jan 21 2025 Switched from lnav back to colortail
Thu Oct 17 2024 Added neo and cbonsai to information display
Thu Sep 05 2024 Removed "blocking" option (mv to another script)
Wed May 29 2024 Added "text Effects" (https://github.com/ChrisBuilds/terminaltexteffects)
Thu May 02 2024 Cleaned up monitoring loop
Fri Feb 23 2024 Set quote to display at center line of screen
Wed Feb 21 2024 modified ss to resolve names
    Added grc to sar line for cleaner display
Thu Oct 12 2023 modified "vnstat -hg" line in default monitor to add some color
'

# 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

-4  # 404 report
-e  # Edit lighttp.conf
-c  # Edit Colortail config
-g  # GoAccess
-h  # Httping
-l  # View logs
-Q  # Query web log
-s  # Server status
-S  # ${BY}Server control${N}
-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 goaccess >/dev/null || sudo apt install goaccess -yyq
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}]----

$(cat ~/.host) / $(fclock) 

4. ${BY}404 report${N}
e. Edit lighttp.conf
c. Edit Colortail config
g. GoAccess
h. Httping
l. View logs
Q. Query web log
s. Server status
S. Server control
t. Trafic monitor
-----------------------
q. ${BY}Quit${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
    4) # 404 report
    clear
    bat --style grid /var/log/lighttpd/error.log
    pause
    grep 404 $ACCESS | awk '{print $7}' | grep -E 'mp3$|html$|pdf$'|sort |uniq -c | sort -n|bat --style grid
    # 404 check on mp4 files
    cd /var/www || exit 1
    echo "$NAME: Checking mp4 files"
    for MP4 in $(grep src media.md |cut -d\" -f2|egrep -v '100\%|preload')
    do
        PNG=$(echo "$MP4"|sed s/mp4/png/1)
        [ ! -f "${BASE}${MP4}" ] && echo "Missing: $MP4"
        [ ! -f "${BASE}${PNG}" ] && echo "Missing: $PNG"
    done
    for MP4 in $(grep src health.md |cut -d\" -f2|egrep -v '100\%|preload')
    do
        PNG=$(echo "$MP4"|sed s/mp4/png/1)
        [ ! -f "${BASE}${MP4}" ] && echo "Missing: $MP4"
        [ ! -f "${BASE}${PNG}" ] && echo "Missing: $PNG"
    done
    pause
    ;;
    c) # edit conf
    clear
    sudo vi /etc/colortail/conf.colortail
    log "edit /etc/colortail/conf.colortail"
    pause
    ;;
    e) # edit conf
    clear
    sudo vim /etc/lighttpd/lighttpd.conf
    log "edit /etc/lighttpd/lighttpd.conf"
    lighttpd -tt -f /etc/lighttpd/lighttpd.conf
    pause
    ;;
    g) # goaccess
    xtitle "web: GoAccess"
    cd /var/log/lighttpd || exit 1
    if [ -f access.log.2.gz ]
    then
        zcat access.log.*.gz | goaccess --config-file=/etc/goaccess/goaccess.conf  --enable-panel=GEO_LOCATION access.log access.log.1 --log-format=COMBINED -e DeviceDHCP.Home -e "192.168.0.167" -e "192.168.0.178" -e "192.168.0.1" --ignore-crawlers;
    else
        goaccess --config-file=/etc/goaccess/goaccess.conf --enable-panel=GEO_LOCATION access.log access.log.1 --log-format=COMBINED -e DeviceDHCP.Home  -e "192.168.0.167" -e "192.168.0.178" -e "192.168.0.1" -e server9.hobohost.com --ignore-crawlers
    fi
    cd - >/dev/null || exit 1
    ;;
    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"
    trap - 2
    trap "continue" 2 # allow ctrl-c to stop, but not end session
    colortail -q -f /var/log/auth.log -f /var/log/lighttpd/access.log
    ;;
    t) # Traffic
    xtitle "Web: Traffic"
    clear
    sudo iptraf-ng -i enp2s0
    ;;
    s) # server status
    xtitle "Web: status"
    clear
    sudo service lighttpd status
    ;;
    S) # start/stop server
    xtitle "Web: Control"
    clear
    echo -n "${G}start${N}, ${R}stop${N}, status, or ${BY}reload${N}: "
    read -r OPTION
    log "running: service lighttpd $OPTION"
    [ "$OPTION" != "status" ] && sudo service lighttpd "$OPTION"
    tput cup $ROWS $[$COLS/2];spinit sleep  7;clear
    sudo service lighttpd status
    sudo systemctl status netfilter-persistent.service
    sudo /sbin/iptables-save
    pause
    ;;
    Q) # Query log
    xtitle "Web: Query"
    clear
    FZF_DEFAULT_OPTS="-m --prompt='▶' --pointer='→' --marker='♡' --ansi";cat /var/log/lighttpd/access.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 "Web: Hardware"
        clear
        neofetch --ascii_distro linuxmint_small
        echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
        # Logs
        xtitle "Web: logs"
        timeout  --foreground 2m colortail -q -f /var/log/auth.log -f /var/log/lighttpd/access.log
        # sar
        clear
        xtitle "Web: SAR"
        if [ $(date +%H) -lt 2 ]
        then
            grc sar;
            echo " "
            vmstat -a --unit m 1 3
        else
            grc sar -s $(date -d "2 hours ago" +%H):00:00;
            echo " "
            grc vmstat -a --unit m
        fi
        echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
        # Network 
        clear
        xtitle "Web: Network"
        center "-| Network Scan |-"
        line
        grc nmap -sn --system-dns 192.168.0.1-253
        echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
        clear
        xtitle "Web: Connections"
        echo "$BG"
        center "-| Connections |-"
        echo -n "$BC"
        grc last -5 -adx
        line
        ssh -q -tt laptop ~/bin/stats
        echo " ";tput cup $ROWS $[$COLS/2];spinit sleep 30;
        # stats
        clear
        xtitle "Web: 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 "Web: 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 "Web: nmon"
        # nmon
        timeout  --foreground 2m  nmon
        clear
        xtitle "Web: 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