#!/bin/bash 

# Title......: u
# Description: A utility menu
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Sat 04 Nov 2023 10:12:17 AM CDT
#----------------------------------

: ' Changes
Sat Oct 21 2023 cleaned up code and rm cursor during backup
Thu Oct 12 2023 removed "colout" from pip update check
'
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
TIMEFORMAT="${BY}Elapsed time:${BG} %E${N}"
PATH=$PATH:~/.local/bin
WEB='/var/www'
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

# 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
#----------------------------------
bl(){ ## write a blank line
    # Use: bl
    [ "$DEBUG" == "1" ] && set -x
    echo ""
}

html(){ ## create html from 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" "$*"
}

backup() ## rsync to BACKUP
    { 
        tput civis # turn off cursor
        log "backup started"
        cd || exit 1

        gio trash --empty # clear trash first

# backup to microSD card if mounted
if [ -d /media/mitch/bu-volume1/ ]
then
    log "usb bu-volume1"
    xtitle "backup: bu-volume1"
    log "rsync: backup"
    sudo rsync -aHh --ignore-errors --delete --info=progress2 --exclude='clips' --exclude='Downloads' --exclude='Temp' /etc /etc/goaccess /home /var/www /var/gopher /media/mitch/bu-volume1/ 2>/dev/null
    BU="yes"
elif [ -d /media/mitch/bu-volume2 ]
then
    xtitle "backup: bu-volume2"
    log "backup: bu-volume2"
    sudo rsync -aHh --ignore-errors --delete --info=progress2 --exclude='clips'--exclude='Downloads' --exclude='Temp' /etc /etc/goaccess /home /var/www /var/gopher /media/mitch/bu-volume2/ 2>/dev/null
    BU="yes"
fi

[ "$BU" != "yes" ] && return
duf -only local
# Clear any accidental input during backup:
read -r -t 1 -n 10000 discard
echo "------------------"
echo "- All backed up! -"
echo "------------------"
echo "${BY}Wait! Syncing Drives...${N}"
spinit sync
echo "...done"
echo "${G}It's safe to remove the USB drive now.${N}"
[ -d /media/mitch/bu-volume1/www ] && eject /media/mitch/bu-volume1/
[ -d /media/mitch/bu-volume2/www ] && eject /media/mitch/bu-volume2/
log "backup completed"
tput cnorm # turn cursor back on
cd - >/dev/null || exit 1
}

# 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 utility menu/wrapper

-a          # display auth.log
-b          # perform backup
-h          # display this help
-i          # display system information
-l          # display syslog
-u          # update system
-W          # watch iptables filtering

${BY}No option starts menu${N}
END
exit
fi

# listing of required apps
command -v bash >/dev/null || sudo apt install bash -qyy
command -v boxes >/dev/null || sudo apt install boxes -qyy
command -v duf >/dev/null || sudo apt install duf -yyq
command -v htop >/dev/null || sudo apt install htop -yyq
command -v iftop >/dev/null || sudo apt install iftop -yyq
command -v lnav >/dev/null || sudo apt install lnav -yyq
command -v mc >/dev/null || sudo apt install mc -yyq
command -v multitail >/dev/null || sudo apt install multitail -yyq
command -v rsync >/dev/null || sudo apt install rsync -qyy
command -v neofetch >/dev/null || sudo apt install neofetch -yyq
command -v vd >/dev/null || sido apt install visidata -yyq

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

while :
do
    if [ $# -lt 1 ] # check to see if a command line argument is passed
    then
        clear
        xtitle "Utilities"
echo ",----[${BC}Utilities${N}]"
echo "
${BC}$(uname -n) / $(fclock) ${N}

a. Auth log
b. Backup system
c. Cpu Information
C. Conky config
g. Gotop
I. Iftop
i. Information
l. Log (syslog)
m. Midnight Commander
p. Ping
t. Htop
u. Update
w. wtmptail
${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 
        a) # auth
            clear
            xtitle auth.log
            lnav /var/log/auth.log
            ;;
        b) # backup
            clear
            time backup
            ;;
        c) # cpu-x
            cpu-x -n
            ;;
        C) # conkyrc 
            vim ~/.conkyrc
            ;;
        g) # gotop
            gotop
            ;;
        i) # System info
            xtitle "System Info"
            cd ~ || exit 1
            clear
            neofetch 
            [ $# -eq 0 ] && pause
            echo "----------------------"
            command -v freec >/dev/null && freec -h;echo " "
            echo "----------------------"
            pause
            duf -only local
            pause
            sar -s "$(date -d "1 hours ago" +%H):00:00"
            [ $# -eq 0 ] && pause
            ;;
        I) # iftop
            xtitle iftop
            clear
            sudo iftop -i wlp1s0
            ;;
        m) # midnight commander
            mc
            ;;
        p) # ping
            xtitle ping
            clear
            echo -n "IP or host: "
            read -r OPTION
            ping -c 10 "${OPTION:=8.8.8.8}"
            pause
            ;;
        l) # syslog
            xtitle syslog
            clear
            lnav /var/log/syslog
            ;;
        t) # Htop
            xtitle Htop
            htop
            ;;
        u) # update
            time {
            clear
            xtitle Update
            log "performing updates"
             command -v pip >/dev/null && pip install --upgrade pip
             command -v pip >/dev/null && pip install --upgrade visidata
             command -v pip >/dev/null && pip install --upgrade epy-reader
             command -v pip >/dev/null && pip install --upgrade rsstail
            command -v tldr >/dev/null && tldr --update
            sudo apt-get update
            sudo apt-get upgrade -yyq
            sudo apt-get autoremove
            sudo apt-get autoclean
            }
            ;;
        w) # wtmptail
            xtitle wtmp
            multitail -cS wtmptail -l wtmptail -n 15
            ;;
        W) # watch iptable filtering
            sudo prewatch --interval 0 'iptables -vL'
            ;;
        q) # quit
            clear
            bl
            echo "Bye"
            exit 
            ;;
        !) # run command
            xtitle "Run command"
            clear
            echo "${BY}Hit return with ${R}no${N}${BY} 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
            ;;
        *) # screen saver
            # this code is calling a program I wrote for conkey that displays rss, system data, and more on desktop
            tput civis # turn off cursor
            while :
            do
                clear
                dtinfo 2>/dev/null
                read -s -t 15 -n 1 x
                [ "$x" == "q" ] && break
                [ "$x" == "p" ] && read -p '--Paused--' -n1 x
            done
            tput cnorm # turn cursor back on
            ;;
    esac
    [ $# -eq 1 ] && exit
done