#!/bin/bash
# RadioWebSystem - AirCheck Recorder (Nahravani hodinoveho vysilani)

# 1. Prechod do slozky se skriptem a priprava cile
cd "$(dirname "$0")"
mkdir -p airchecks

# 2. Cekani na presnou celou hodinu (pokud je spusteno v 59. minute)
CURRENT_MIN=$(date +%M)
if [ "$CURRENT_MIN" == "59" ]; then
    SEC_LEFT=$((60 - $(date +%S)))
    if [ $SEC_LEFT -gt 0 ] && [ $SEC_LEFT -le 60 ]; then
        sleep $SEC_LEFT
    fi
fi

# 3. Ziskani aktualniho data a casu pro nazev souboru
DATE_STR=$(date +"%Y-%m-%d_%H-00")
TEMP_FILE="airchecks/raw_${DATE_STR}.mp3"
FINAL_FILE="airchecks/AirCheck_${DATE_STR}.mp3"

# 4. Ziskani URL streamu napevno jako konstantu
STREAM_URL="http://live.topradio.cz:8000/crazy128"
RETENTION_DAYS=31

if [ -z "$STREAM_URL" ]; then
    echo "Stream URL nenalezena v nastaveni."
    exit 1
fi

# 4.5 Ochrana mista na disku (Minimalne 500 MB volneho mista)
MIN_FREE_MB=500
while true; do
    FREE_MB=$(df -Pm . | awk 'NR==2 {print $4}')
    if [ -z "$FREE_MB" ] || [ "$FREE_MB" -ge "$MIN_FREE_MB" ]; then
        break
    fi
    
    OLDEST_FILE=$(ls -tr airchecks/AirCheck_*.mp3 2>/dev/null | head -n 1)
    if [ -n "$OLDEST_FILE" ] && [ -f "$OLDEST_FILE" ]; then
        rm -f "$OLDEST_FILE"
    else
        break
    fi
done

# 5. Zastaveni predchoziho nahravani (pokud bezi z minule hodiny)
if [ -f "airchecks/aircheck.pid" ]; then
    OLD_PID=$(cat airchecks/aircheck.pid)
    if [ -n "$OLD_PID" ]; then kill $OLD_PID 2>/dev/null; fi
    rm -f airchecks/aircheck.pid
fi

# 6. Spusteni NOVEHO nahravani na pozadi (nohup zajisti beh i po ukonceni skriptu)
nohup curl -s "$STREAM_URL" -o "$TEMP_FILE" >/dev/null 2>&1 &
NEW_PID=$!
echo $NEW_PID > airchecks/aircheck.pid

# 7. Zpracovani a prevod zbylych raw_*.mp3 souboru z minulych hodin
for RAW_FILE in airchecks/raw_*.mp3; do
    if [ ! -f "$RAW_FILE" ]; then continue; fi
    if [ "$RAW_FILE" == "$TEMP_FILE" ]; then continue; fi
    
    BASE_NAME=$(basename "$RAW_FILE" .mp3 | sed 's/^raw_//')
    OUT_FILE="airchecks/AirCheck_${BASE_NAME}.mp3"
    
    if command -v ffmpeg &> /dev/null; then ffmpeg -y -i "$RAW_FILE" -codec:a libmp3lame -b:a 128k "$OUT_FILE" < /dev/null > /dev/null 2>&1; rm -f "$RAW_FILE" 2>/dev/null; else mv "$RAW_FILE" "$OUT_FILE"; fi
done

# 8. Promazani nahravek
if [ -z "$RETENTION_DAYS" ] || [ "$RETENTION_DAYS" -le 0 ]; then
    RETENTION_DAYS=31
fi
find airchecks/ -name "AirCheck_*.mp3" -type f -mtime +$RETENTION_DAYS -delete