#!/bin/bash

# Check if URL is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <m3u8_url>"
    exit 1
fi

URLx="$1"
URL="${URLx%%\\?*}"

echo URL

OUTPUT="output.aac"

# Check if destination file exists
if [ -e "$OUTPUT" ]; then
    n=1
    # Loop to find a unique filename by appending a number
    while [ -e "${n}${OUTPUT}" ]; do
        ((n++))
    done
    new_dest="${n}${OUTPUT}"
    echo "File exists. Renaming to $new_dest"
    
    OUTPUT="$new_dest"
fi

echo "Analyzing stream with ffprobe..."

# Find the first audio stream index that is stereo (2 channels) and AAC codec
STREAM_INDEX=$(ffprobe -v error -show_entries stream=index,codec_name,channels -of csv=p=0 "$URL" | \
awk -F, '$2=="aac" && $3==2 {print $1; exit}')

# Check if a matching stream was found
if [ -z "$STREAM_INDEX" ]; then
    echo "Error: No stereo AAC audio stream found."
    exit 1
fi

echo "Found matching stereo AAC stream at index: $STREAM_INDEX"
echo "Downloading AAC audio..."

#rm -f output.aac

# Extract the specific stream and convert to lowest quality MP3 (CBR 32k or VBR 9)
ffmpeg -v error -y -i "$URL" -map 0:a:"$STREAM_INDEX" -c copy "$OUTPUT"

echo "Done! Saved to $OUTPUT"