#!/bin/bash

set -x

# Get current month and year
current_month=$(date +%m)
current_year=$(date +%Y)

# Determine the music directory based on the current month
music_base_dir='/home/user/drives/local-2tb/music/4 Seasons'

# For the 1st day of the month, use last month's music, otherwise use the current month's music
if [ "$(date +%d)" -eq 01 ]; then
    # Use the previous month's music
    music_file=$(find "$music_base_dir" -type f -name "$(date --date="last month" +%m)*" | head -n 1)
else
    # Use the current month's music
    music_file=$(find "$music_base_dir" -type f -name "${current_month}*" | head -n 1)
fi

# Check if the music file exists
if [ ! -f "$music_file" ]; then
    echo "Music file not found!"
    exit 1
fi

# Get the duration of the music file in seconds
music_duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$music_file")
echo "Music duration: $music_duration seconds"

# Calculate the number of days in the current month using `date`
days_in_month=$(date -d "$(date +%Y-%m-01) +1 month -1 day" +%d)
echo "Number of days in the current month: $days_in_month"

# Target total video duration (music duration + 3 seconds)
target_total_duration=$(echo "$music_duration + 3" | bc)
echo "Target total video duration (music + 3 seconds): $target_total_duration seconds"

# Calculate the target duration per video
target_duration_per_video=$(echo "$target_total_duration / $days_in_month" | bc -l)
echo "Each day's target video length: $target_duration_per_video seconds"

# Calculate the date for yesterday
yesterday=$(date --date="yesterday" +%Y-%m-%d)
echo "Processing images for yesterday: $yesterday"

# Get the directory of the script
script_dir=$(dirname "$(readlink -f "$0")")

# Extract the base directory and the first word of the script's folder name
base_dir="/home/user/drives/local-2tb"
first_word_of_script_folder=$(basename "$script_dir" | cut -d'-' -f1)

# Define the directory where images are stored
image_dir="$base_dir/$first_word_of_script_folder/$yesterday"

# Count the total number of images (JPEG files)
total_images=$(find "$image_dir" -type f -name "*.jpg" | wc -l)

# If no images are found, exit
if [ "$total_images" -eq 0 ]; then
    echo "No images found in $image_dir."
    exit 1
fi

# Create a new directory for the output video based on year and month
output_date=$(date +"%Y-%m")  # yyyy-mm format
output_dir="$base_dir/movies/$first_word_of_script_folder/$output_date"
mkdir -p "$output_dir"

# Define the output video path
output_video="$output_dir/${yesterday}_${first_word_of_script_folder}-day.mp4"

# If the video already exists, rename the output file to avoid overwriting
if [ -f "$output_video" ]; then
    echo "File already exists, renaming the file..."
    output_video="$output_dir/${yesterday}_${first_word_of_script_folder}-day-4month.mp4"
fi

# Create a temporary text file with the sorted list of image paths
temp_file=$(mktemp)
find "$image_dir" -type f -name "*.jpg" | sort -n | while read image; do
  echo "file '$image'" >> "$temp_file"
done

# Calculate the number of images
num_images=$(wc -l < "$temp_file")
echo "Total images found for the video: $num_images"

# If there are fewer than 1 image, exit
if [ "$num_images" -lt 1 ]; then
    echo "No images found, exiting."
    exit 1
fi

# First, create the video using default frame rate (no speed-up or slow-down yet)
echo "Creating video at default frame rate..."
ffmpeg -f concat -safe 0 -i "$temp_file" -c:v libx264 -pix_fmt yuv420p -crf 28 -vsync 2 -y "$output_video"

# Check the duration of the created video
video_duration=$(ffmpeg -i "$output_video" 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//)
echo "Initial video duration: $video_duration"

# Get the video duration in seconds (from HH:MM:SS format)
IFS=':' read -r hours minutes seconds <<< $(echo $video_duration | cut -d '.' -f1)  # Extract time
total_seconds=$(($hours * 3600 + $minutes * 60 + $seconds))  # Convert to total seconds

# Calculate the speed-up factor to make the video fit into the target duration
speed_up_factor=$(echo "scale=3; $total_seconds / $target_duration_per_video" | bc)
echo "Calculated speed-up factor: $speed_up_factor"

# Adjust the playback speed using the setpts filter to make the video fit into the target duration
final_video="$output_dir/${yesterday}_${first_word_of_script_folder}-day-4month.mp4"
ffmpeg -i "$output_video" -filter:v "setpts=PTS/$speed_up_factor" -y "$final_video"

# Check the duration of the adjusted video
adjusted_duration=$(ffmpeg -i "$final_video" 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//)
echo "Adjusted video duration: $adjusted_duration"

# Check for ffmpeg success
if [ $? -ne 0 ]; then
  echo "Error: ffmpeg failed to create the final video."
  exit 1
fi

# Inform user the video has been created
echo "Video created at $final_video"

# Clean up the temporary file
rm "$temp_file"
