#!/bin/bash
######################################################################
#                                                                    #
#      DO NOT EDIT THIS  FILE !!!                                    #
#                                                                    #
#  Calculates the next png to show for animation.lua                 #
#                                                                    #
#  Scripted by Koentje  (remon@cobrasoft.nl)                         #
#                                                      version 1.0   #
######################################################################

if [ "$1" = "" ]; then
  echo -e "\n\e[31m  Can only be started from within animation.lua!\e[m\n"
  exit
fi

# Normal or reversed animation
if [ "$2" = "" ]; then
  SORT="sort -V"
elif [ "$2" = "reverse" ]; then
  SORT="sort -Vr"
elif [ "$2" = "r" ]; then
  SORT="sort -Vr"
else
  SORT="sort -V"
fi

# Directory containing the next image to show
DIR="$1"
if [ ! -d "$DIR/current" ]; then
 mkdir "$DIR/current"
fi

# File to store the current image index in
INDEX_FILE="$DIR/current/conky_slideshow_index"

# Get list of image files in normal or reversed sort order
FILES=($(ls "$DIR"/*.png "$DIR"/*.jpg 2>/dev/null | $SORT))

# If the list of files is empty (empty PNG folder), exit script
if [ "${#FILES[@]}" -eq "0" ]; then
  exit 1
fi

# Force the index to start at 0 on the first run or if INDEX_FILE is missing
if [ ! -f "$INDEX_FILE" ]; then
  INDEX=0
else
  INDEX=$(cat "$INDEX_FILE")
fi

# Ensure the index is within the bounds of the file list
INDEX=$((INDEX % ${#FILES[@]}))

# Copy the current image to the target location
cp "${FILES[$INDEX]}" "$DIR/current/current.png"

# Increment the index for the next run
INDEX=$((INDEX + 1))

# Save the next index
echo "$INDEX" > "$INDEX_FILE"
