#!/usr/bin/bash

while true; do

echo "" > /var/www/kroobot.net/liquidsoap/play02.txt
    
TARGET_DIR="/var/www/kroobot.net/station02"
MP3_FILES=()

shopt -s nullglob

while IFS= read -r -d '' file; do
    MP3_FILES+=("$file")
done < <(find "$TARGET_DIR" -maxdepth 1 -name "*.mp3" -print0)

# Loop through the array
for f in "${MP3_FILES[@]}"; do

echo $f > /var/www/kroobot.net/liquidsoap/play02.txt

echo "$(date +'%Y-%m-%d %H:%M:%S')"  > /var/www/kroobot.net/liquidsoap/time02.txt

# Get the current minute
current_minute=$(date +%-M)

# Determine the remaining minutes until the next top or half hour
if [ "$current_minute" -lt 15 ]; then
    minutes_to_wait=$((15 - current_minute))
elif [ "$current_minute" -lt 30 ]; then
    minutes_to_wait=$((30 - current_minute))
 elif [ "$current_minute" -lt 45 ]; then
    minutes_to_wait=$((45 - current_minute))
else
    minutes_to_wait=$((60 - current_minute))
fi

# Convert to seconds and wait (subtracting current seconds for exactness)
seconds_to_wait=$((minutes_to_wait * 60 - $(date +%-S)))  
 
# Sleep until the calculated time
#echo "Sleeping for $seconds_to_wait seconds..."
sleep "$seconds_to_wait"

/usr/bin/ffmpeg -re -i $f -c:a libmp3lame -b:a 128k  -content_type audio/mpeg -f mp3  'icecast://source:hackme@localhost:8000/station02' 

echo "" > /var/www/kroobot.net/liquidsoap/time02.txt

done
  
done