#!/bin/bash 

# Title......: lm
# Description: list media
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org 
# Updated....: Tue Jul 21 12:14:58 AM CDT 2026
#----------------------------------

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

: ' Changes
Sun Jul 06 2025 Added ability to handle file wild cards
Sun Jun 01 2025 Added display of video res and audio bit rate, fix total display to support mp3
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
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
LOG=~/etc/${HOSTNAME}.log                  # my log file

# 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)                          # bold 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(){ ## 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}   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
}

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" "$*"
}

version(){ ## display version and change history
    grep -E '^# Updated' $0
    bl
    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
    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   # list media, displays mp4's and mp3's in a directory and gives run time

${BG}lm${N} ${BY}{/path}${N}

         # no option performs listing in current directory
{/path}  # performs function on path noted

${UL}List mp4 files first and then mp3 files.${N}
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 ffmpeg >/dev/null || sudo apt install ffmpeg -yyq 
command -v exiftool >/dev/null || sudo apt install libimage-exiftool-perl -yyq 

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

[ "$#" -eq 1 ] && [ -d $1 ] && cd $1 && shift 1          # one option and its for directory

## No media, just do  file listing
if [ $(ls -A *.mp? *.m4v 2>/dev/null|wc -l) -lt 1 ]
then
    ls
    exit 
fi
if [ "$#" -gt 0 ] 
then
    list="$@" 
else
    list="$(\ls -v *.mp?)"
fi
for f in $list
    do
        chmod a-x *.mp? # rm the executable that come from winblows
        if [ "${f##*.}" == "mp4" ]
        then
            RES="${BC}$(ffmpeg -i $f 2>&1 | grep "Video:" | grep -Po "\d{3,5}x\d{3,5}")$N"
        else
            RES="${BC}$(ffmpeg -i $f 2>&1 |grep 'Audio:'|cut -d',' -f5)$N"
        fi
        ffmpeg -i "$f" 2>&1 | grep --color=always Duration | cut -d " " -f 4 | sed s/,// | tr -d "\n" && echo -n " $RES " && ls --color "$f";
    done

## display total
bl 
[ $(\ls *mp3 2>/dev/null|grep -c mp3) -gt 0 ] && echo "${BY}mp3 Total:${N} $(exiftool -n -q -p '${Duration;our $sum;$_=ConvertDuration($sum+=$_) }' ./*.mp3 2>/dev/null| tail -n1)$N"
[ $(\ls *mp4 2>/dev/null|grep -c mp4) -gt 0 ] && echo "${BY}mp4 Total:${N} $(exiftool -n -q -p '${Duration;our $sum;$_=ConvertDuration($sum+=$_) }' ./*.mp4 2>/dev/null| tail -n1)$N"
bl 

## clean up
[ -f /tmp/$$ ] && rm /tmp/$$ >/dev/null 2>&1 || :
