#!/usr/bin/bash

count=0
read -p "Enter start position: " start

while true; do

php /var/www/kroobot.net/liquidsoap/02aac.php

echo "" > /var/www/kroobot.net/liquidsoap/02play.txt
    
TARGET_DIR="/var/www/kroobot.net/station02"

files=("$TARGET_DIR"/*.aac)
sorted_files=$'\n' files=( $(printf '%s\n' "${files[@]}" | sort -r) )
for file in "${files[@]}"; do

if [ "$count" -ge "$start" ]; then
   
echo $file > /var/www/kroobot.net/liquidsoap/02play.txt

echo "$(date +'%Y-%m-%d %H:%M:%S')"  > /var/www/kroobot.net/liquidsoap/02time.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 $file -c:a copy -f adts -content_type audio/aac 'icecast://source:hackme@localhost:8000/station02' 

echo "" > /var/www/kroobot.net/liquidsoap/02time.txt

else 
((count++))
fi

done
  
start=0
  
done