#!/bin/bash

# Directory containing your images
image_dir="/home/web/public/div.lekvam.no/torvaldbu"
# Directory to store the output videos
output_dir="/home/web/public/div.lekvam.no/torvaldbu"

mkdir -p "$output_dir"

# Font settings for ffmpeg drawtext
fontfile="/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"  # Adjust as needed
fontsize="30"  # Adjust font size as needed
fontcolor="white"  # Adjust font color as needed
x="(w-text_w)/2"  # Position for text: horizontally centered
y="h-th-10"  # Position for text: 10 pixels from the bottom

# Step 1: Process images into daily videos with annotations
for day in $(ls $image_dir | grep 20241218 | grep -oP 'photo_\K\d{8}' | sort -u); do
    day_video="$output_dir/video_$day.webm"
    if [ ! -f "$day_video" ]; then
        echo "Creating video for $day..."
        ffmpeg -framerate 5 -pattern_type glob -i "$image_dir/photo_${day}_*.jpg" \
               -vf "drawtext=fontfile=$fontfile: text='$day %{frame_num}' : \
                    start_number=0: x=$x: y=$y: fontcolor=$fontcolor: fontsize=$fontsize: box=1: boxcolor=black@0.5" \
               -c:v libvpx-vp9 -b:v 2M -crf 33 "$day_video"
    else
        echo "Video for $day already exists."
    fi
done

# Step 2: Concatenate all daily videos into one
# echo "Concatenating all videos..."
# concat_list=$(mktemp)
# for video in $output_dir/video_*.webm; do
#     echo "file '$video'" >> "$concat_list"
# done
# ffmpeg -f concat -safe 0 -i "$concat_list" -c copy "$output_dir/final_output.webm"
# rm "$concat_list"

echo "All operations completed."
