#!/bin/bash
######################################################################
#Copyright (C) 2026 Kris Occhipinti Films By Kris
#https://filmsbykris.com
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation version 3 of the License.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
######################################################################

file=$1
fn=${1##*/}
dir=${file%$fn}
name=${fn%.*}
ext=${fn#$name}
length="2" # Maximum clip duration
size="240"
fps="15"

echo -n "Scanning ${file} ..."
ffmpeg -i "$file" \
  -filter:v "select='gt(scene,0.4)',showinfo" \
  -f null \
  - 2>&1 | tee ffout | while read l; do echo -n "."; done

echo ""

# set start time stamp to 0
timestamps=(0)

# get time stamps from ffmpeg output
stamps=$(grep showinfo ffout | grep pts_time:[0-9.]* -o | grep [0-9.]* -o | uniq)

# add stamps to array
timestamps+=($stamps)

# Add length of the video to get final time stamps
timestamps+=($(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file"))

# split video into gifs
for ((i = 1; i < ${#timestamps[@]}; i++)); do
  start_time="${timestamps[i - 1]}"
  end_time="${timestamps[i]}"

  # Get the length of the clip based on timestamps
  actual_duration=$(echo "$end_time - $start_time" | bc -l)

  # if clip length is less the script set length then use the shorter length
  final_duration=$(echo "if ($actual_duration < $length) $actual_duration else $length" | bc -l)

  printf -v part '%02d' "$i"
  echo "Processing part $part: Start $start_time, Duration $final_duration..."

  # Run ffmpeg with the calculated final_duration
  ffmpeg -y -nostdin -ss "$start_time" -t "$final_duration" -i "$file" \
    -vf "fps=${fps},scale=${size}:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \
    -loop 0 "$dir$name-$part.gif"

  # add image to html GUI if convertion is successfull
  html="<a href='$dir$name-$part.gif'>
    <img src='$dir$name-$part.gif'>
    </a>
  "
  [[ -f "$dir$name-$part.gif" ]] && echo "$html" >>gifs.html
done

echo "Done! Clips saved to $dir"
