#!/bin/bash

# Title......: pi
# Description: post it - a tool to create html mp4 videos or pictures
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Sun 16 Feb 2025 09:26:24 AM CST
#----------------------------------

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

: ' Changes
Thu Jan 30 2025 Added option to not display comment file
Thu Feb 15 2024 Added version() to display version and changes
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
if [ "$1" == "-n" ] # -n to turn off comments
then
    SKIP=yes
    shift 1
else
    SKIP=no
fi

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
BASE='/var/www'
PDIR=$(cd ..;basename `pwd`)

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

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
}

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

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 {file.mp4|jpg,png,webp}

Generate HTML code with preview for use in web page. By default it will use file in the same directory it is run in. If not found, it will search for it under $BASE, and if found will use that as the location.
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 ffmpegthumbnailer >/dev/null || sudo apt install ffmpegthumbnailer -yyq
command -v ffmpeg >/dev/null || sudo apt install ffmpeg -yyq

# directory check
[[ "$(pwd)" != *"www"* ]] && echo "$NAME: directory error" && exit 1


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

FILE=$1
EXT="${FILE##*.}"

if [[ "$FILE" == *"http"* ]]
then
cat <<END
<div style="padding-bottom:56.25%; position:relative; display:block; width: 100%">
  <iframe width="100%" height="100%"
    src="$1"
    frameborder="0" allowfullscreen="" style="position:absolute; top:0; left: 0">
  </iframe>
</div>
END
exit
fi

case $EXT in
    svg|bmp|jpeg|jpg|png|gif|webp) # picture
        NAME=$(echo $FILE|cut -d'.' -f1|sed -e 's/[-_]/ /g' -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')
        cd /var/www/
        PIC="$(find . -name $1 -print |cut -d'.' -f2-)"
        cd - >/dev/null
        case $PDIR in
            "clips") SIZE="100%" ;;
            *) SIZE="50%";;
esac

# Exceptions 
[ "$(basename $PWD)" == "larkin" ] && SIZE="100%"
[ "$(basename $PWD)" == "linux-desktops" ] && SIZE="100%"
[ "$(basename $PWD)" == "desktops" ] && SIZE="100%"
[ "$(basename $PWD)" == ".house" ] && SIZE="100%"
[ "$(basename $PWD)" == ".family" ] && SIZE="100%"
[ "$(basename $PWD)" == "lisbon-nd" ] && SIZE="100%"
[ "$(basename $PWD)" == "unix" ] && SIZE="100%"
[ "$(basename $PWD)" == "posters" ] && SIZE="75%"
[ "$(basename $PWD)" == "maps" ] && SIZE="75%"
[ "$(basename $PWD)" == "maps-us" ] && SIZE="75%"
[ "$(basename $PWD)" == "work" ] && SIZE="100%"
[ "$(basename $PWD)" == "think" ] && SIZE="85%"
[ "$(basename $PWD)" == "think2" ] && SIZE="85%"
[ "$(basename $PWD)" == "think3" ] && SIZE="85%"
[ "$EXT" == "svg" ] && SIZE="100%"

cat <<END # here docs need to be left justified
[!["$NAME"](${PIC}){width=${SIZE} height=auto}](${PIC} "$NAME")<p>

[🔝](#)
<HR>
END
exit ;; # stop here for picture
    pdf) #pdf
        cd /var/www/
        PDF="$(find . -name $1 -print|cut -d '.' -f2-)"
cat <<END
<iframe src="${PDF}#view=FitH" scrolling="no" width="100%" height="400" style="border:1px solid black;"></iframe> 
END
exit ;;
esac

# Check to see if file is current directory, if not find it
if [ ! -f "$1" ]
then
    cd $BASE
    FOUND=$(find . -name $1 2>/dev/null)
    cd $(dirname $FOUND)
fi

DURATION=$(ffmpeg -i $1 -hide_banner 2>&1 |grep Duration |awk '{print $2}'|cut -d: -f1,2)
FILE="${1%.*}"                   # strip extention
PIC="$FILE.png"                  # png name

if [ ! -f $PIC ] # this determines if the file has been posted before 
then
    ffmpegthumbnailer -i $1 -o $PIC -s 0 -t 15 -f >/dev/null 2>&1 # create png pics from file
    log "Added: $(echo $1|tr '-' ' ')"
fi

# set path/name
cd /var/www
NEW="$(find . -name $1 -print |cut -d'.' -f2-)"
PNG="$(find . -name $PIC -print |cut -d'.' -f2-)"
cd - >/dev/null

# Display code
echo "[__$(echo $FILE|tr '-' ' '|tr '_' ' '|sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')__]($NEW) Duration: $DURATION Posted: $(stat $1|grep Modify|cut -d ' ' -f 2) <video width=\"100%\" height=\"none\" controls=\"controls\" poster=\"$PNG\" preload=\"none\"> <source src=\"$NEW\" preload=\"none\" type=\"video/mp4\"> Your browser does not support the video tag.  </video> " 

## Add comment unless -n was passed
COMMENT="${FILE}.md"
if [ -f "$COMMENT" ] && [ "$SKIP" = "no" ]
then
    bl
    cat $COMMENT
    bl
fi

exit 0