#!/bin/bash

# Title......: timer
# Description: simple bash timer
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Mon May  4 05:48:49 AM CDT 2026
#----------------------------------

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

: ' Changes:
Mon May 04 2026 Cahnges output to single line
Sun May 03 2026 Started script
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
[ "$DEBUG" == 1 ] && echo "---Variables---" && set -x
PS4='$SECONDS $LINENO: '                   # 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
DIR="$(basename $PWD)"                     # location started
PDIR="$(cd ..;basename $PWD)"              # parrent dir
SIT=$(tput sitm)                           # italics
RIT=$(tput ritm)                           # remove italics

# functions
#----------------------------------

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

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

rcf() { ## Function to set random background and foreground colors with contrast
    # Use: rcf "string"

    # Generate random 1-6 for fg/bg to ensure contrast (avoiding 0/7/8)
    local fg=$(( (RANDOM % 6) + 1 ))
    local bg=$(( (RANDOM % 6) + 1 ))

    # Ensure background is not too similar to foreground
    while [ $fg -eq $bg ]; do
        bg=$(( (RANDOM % 6) + 1 ))
    done

    # Apply colors and print
    tput setaf $fg
    tput setab $bg
    tput bold # Make text bold for better readability
    echo -n " $1 "
    tput sgr0 # Reset colors
    #echo ""
}

countdown(){ ## countdown using seconds
    local seconds=$1
    while [ $seconds -gt 0 ]; do
        printf "\r%02d:%02d:%02d " $((seconds/3600)) $(( (seconds/60)%60 )) $((seconds%60))
        xtitle $(printf "\r%02d:%02d:%02d" $((seconds/3600)) $(( (seconds/60)%60 )) $((seconds%60)))
        sleep 1

        : $((seconds--))
    done
    [ $SOUND = "Y" ] && canberra-gtk-play -f /home/mitch/Music/sounds/system/alarm-clock-elapsed.oga
    rcf "Time's up!"
}

# 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

Use:

timer {-s} {time} {"quoted text")

-s   Play sound

Time formats:
  23{s}   Just a number or number with 's' is counted as seconds
  23m     If a 'm' is used it is counted a minutes
  HH:MM:SS  Can be used as well

- It will also change the window title to display count down.

END
exit
fi

# listing of required apps
command -v bash >/dev/null || sudo apt install bash -qyy


# main
#--------------------------- 
[ "$DEBUG" == 1 ] && echo "---Functions---" && typeset -F && read -p "${N}-Continue-" -n 1 x
[ "$DEBUG" == 1 ] && echo "---Main---" && set -x

# check to see if sound is needed
if [ "$1" = "-s" ]
then
    export SOUND=Y
    shift
else
    export SOUND=N
fi

case "$1" in
    *":"*) # time format 00:00:00
        time_str="$1"
        IFS=: read -r h m s <<< "$time_str"
        SEC=$((10#$h * 3600 + 10#$m * 60 + 10#$s))
        ;;
    *"m"*) # time format for just minutes 4m
        TRIM=$(echo $1 |sed 's/m//g')
        SEC=$(( $TRIM * 60 ))
        ;;
    *) # else assume just seconds 
        TRIM=$(echo $1 |sed 's/s//g')
        SEC=$TRIM
        ;;
esac

countdown $SEC
[ "$#" -eq 2 ] && echo -e " ${SIT}${2}${RIT}" || echo ""

exit

# vim: nospell ft=sh