#!/bin/bash

# Title......: lib
# Description: bash functions and variables designed to be sourced
# Author.....: Mitchell Johnston
# Date.......: Thu Jul 01 2021 
#----------------------------------

# shellcheck disable=SC2034
# shellcheck disable=SC2153

#======================================================
# variables
#======================================================
# colors - foreground
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
BB=$(tput setaf 4; tput bold)              # bold blue
M=$(tput setaf 5)                          # magenta
BM=$(tput setaf 5; tput bold)              # bold magenta
C=$(tput setaf 6)                          # cyan
BC=$(tput setaf 6; tput bold)              # bold cyan
L=$(tput setaf 7)                          # light grey
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
RC=$(tput setaf $((RANDOM % 256)))         # random 256 color
ROWS=$(tput lines)

# colors - background
RBG=$(tput setab 1)                         # red background
BRBG=$(tput setab 1 ; tput bold )           # light red background
GBG=$(tput setab 2)                         # green background
BGBG=$(tput setab 2 ; tput bold )           # light green background
YBG=$(tput setab 3)                         # yellow background
BYBG=$(tput setab 3 ; tput bold )           # light yellow background
BBG=$(tput setab 4)                         # blue background
BBBG=$(tput setab 4 ; tput bold )           # light blue background
MBG=$(tput setab 5)                         # purple background
BMBG=$(tput setab 5 ; tput bold )           # light purple background
CBG=$(tput setab 6)                         # cyan background
BCBG=$(tput setab 6 ; tput bold )           # light cyan background
WBG=$(tput setab 7)                         # white background
BWBG=$(tput setab 7 ; tput bold )           # light white background

# standard
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
LOG=~/etc/${HOSTNAME}.log                  # my log file
DEBUG=0 

#======================================================
# functions
#======================================================
banner(){ ## to replace banner app from sys-v
	# Use: banner "text"
figlet -f /usr/share/figlet/banner.flf $1
}

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

data(){ ## parses self for data elements
	# all data elements should be listed below a line that starts w/ ===DATA===
	# and an exit statement should be before it in the code.
	[ $DEBUG == 1 ] && set -x
    sed -n '/^===DATA===/,$p' <$0|grep -v '===DATA==='
}

display(){ ## show display settings
	# Use: display (no options)
	[ $DEBUG == 1 ] && set -x
	if [ -z $DISPLAY ]
    then
		echo "$(w|tail -1|awk '{print $3}') $TERM $(tput lines)r x $(tput cols)c"
    else
		echo "$DISPLAY $TERM $(tput lines)r x $(tput cols)c"
	fi
}

error(){ ## exit w/ message on error
	# Use: {cmd} || error "Text"
	[ $DEBUG == 1 ] && set -x
	echo "${BR}$*$N"
	exit 1
}

extract(){ ## handy archive extraction
	# Use: extract {file}
	[ $DEBUG == 1 ] && set -x
	if [ -f $1 ]
	then
		case $1 in
			*.tar.bz2)   tar xvjf $1     ;;
			*.tar.gz)    tar xvzf $1     ;;
			*.bz2)       bunzip2 $1      ;;
			*.rar)       unrar x $1      ;;
			*.gz)        gunzip $1       ;;
			*.tar)       tar xvf $1      ;;
			*.tbz2)      tar xvjf $1     ;;
			*.tgz)       tar xvzf $1     ;;
			*.zip)       unzip $1        ;;
			*.Z)         uncompress $1   ;;
			*.7z)        7z x $1         ;;
			*)           echo "${BR}$1 ${N}cannot be extracted via >extract<"
						file $1;;
		esac
	else
		echo "${BR}$1 $N is not a valid file"
	fi
}

future(){ ## display with figlet
	# Use: future {text}
	toilet --metal -f future "$*"
}

lineit(){ ## pass 2 args, 1st text, 2nd number of copies to print
	# Use: lineit "=" (Create line of "=" terminal wide
	#      lineit "-+"  20   (Create line of "-+" 20 characters wide)
	[ $DEBUG == 1 ] && set -x
		CHAR=$(echo -n "$1" |wc -c) # get the number of characters in first argument
		CNT="${2:-$(tput cols)}"    # set count to 2nd argument
		[ "$CHAR" -gt 1 ] && CNT=$(($CNT/$CHAR)) # divide $CNT if needed
        until [ $CNT -eq 0 ]
        do
                echo -n "$1"
				CNT=$(($CNT - 1))
        done
		echo ""                     # send new line
}

log(){ ## creates a basic log entry $LOG must be defined
	# Use: log {entry}   or log (no option to view)
	[ "$DEBUG" == "1" ] && set -x
	if [ "$#" -eq 0 ] # if not adding then display lat 7 entries
	then
		echo $BC
		vd $LOG 2>/dev/null ||tail -7 $LOG # display with VisiData, if installed
		echo $N
	else
		echo -e "$(date '+%D%t%T')\t${NAME}\t$*">>"$LOG"
	fi
}

mdv(){ ## markdown viewer - cli
	# Use: mdv {file}
	pandoc $1| lynx -stdin
}

mod_script(){ ## modify script inside a case statement or can be used in a if test
	# Use: mod_script
	[ "$DEBUG" == "1" ] && set -x
	if [ "$NAME" == "bash" ]
	then
		log "modified: .bashrc"
		vim ~/.bashrc
	else
		log "modified: $(basename $0)"
		vim $0
	fi
}

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
}

rcb(){ ## random color function - changes each time its called
	# Use: rcb; {cmd}
	tput setab $((RANDOM % 256))      
}

rcf(){ ## random color foreground - changes each time its called
	# Use: rcf; {cmd}
	tput setaf $((RANDOM % 256))      
}

ren(){ ## fix names (rename)
	# Use: ren {file}
	[ $DEBUG == 1 ] && set -x
	[ "$(pwd)" == "$HOME" ] && return
	for FILE in "$@"
	do
		[ -z "$FILE" ] && return
		if [[ "$FILE" == *"epub"* ]]
		then
			NEW=$(echo "$FILE"|tr [A-Z] [a-z] | sed 's/[^[:alnum:].-]//g' |tr -cs '[:alnum:]')
		else
			NEW=$(echo "$FILE"|tr [A-Z] [a-z] | sed 's/[[:blank:]]/-/g;s/[^[:alnum:].-]//g' |tr -cs '[:alnum:]')
		fi
		[ "$FILE" != "$NEW" ] && mv -v "$FILE" "$NEW" 2>/dev/null
	done
}

resize(){ ## Dynamically display terminal window size with text centering
    # Use: resize   - then change window, when set, control-c
	tput smcup
redraw() { ### function in a function, because you can
	local str width height length
	
	width=$(tput cols)
	height=$(tput lines)
	str="Width = $width Height = $height"
	length=${#str}
	clear
	tput cup $((height / 2)) $(((width / 2) - (length / 2)))
	echo "$str"
}

trap redraw WINCH  # signal is sent each time the terminal window is resized

redraw
while true
do
	:
done
}

s2m(){ ## seconds to  days, hours, minutes, seconds
	# Use: s2m {seconds}
    num=$1
    min=0
    hour=0
    day=0
    if((num>59));then
        ((sec=num%60))
        ((num=num/60))
        if((num>59));then
            ((min=num%60))
            ((num=num/60))
            if((num>23));then
                ((hour=num%24))
                ((day=num/24))
            else
                ((hour=num))
            fi
        else
            ((min=num))
        fi
    else
        ((sec=num))
    fi
    echo "$day"d "$hour"h "$min"m "$sec"s
}

title(){ ## write out a title
	# Use: title "Some text to make a title"
	[ $DEBUG == 1 ] && set -x
    TEXT="$*"
    LENGTH=$(echo -n $TEXT|wc -c)
    echo $TEXT
    lineit "-" $LENGTH
}

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