#!/bin/bash

# Script for rotations to audio card and to live stream from on old Pi1B running Raspbian 12.

# Variables for Icecast/Shoutcast provider
HOST="localhost"  # Server hostname or IP
PORT=8000         # Server port
PASSWORD="hackme" # Source password
MOUNTPOINT="/stream.mp3"  # Mountpoint (for Icecast); for Shoutcast, often "/"
IS_ICECAST=1      # 1 for Icecast, 0 for Shoutcast
PLAYLIST_DIR="./music"  # Directory containing audio files (mp3 and wav supported)

# Ensure required tools are installed: ezstream, mpg123, sox, lame, festival (text2wave), shuf
# sudo apt install ezstream mpg123 sox lame festival coreutils

# Get list of audio files
files=($(find "$PLAYLIST_DIR" -type f \( -name "*.mp3" -o -name "*.wav" \)))

# Shuffle the files
shuffled_files=($(shuf -e "${files[@]}"))

# Build play sequence with jingle every 4th position
play_sequence=()
count=0
for file in "${shuffled_files[@]}"; do
  play_sequence+=("$file")
  ((count++))
  if ((count % 3 == 0)); then
    play_sequence+=("./jingle.wav")
  fi
done

# Create temporary directory
tempdir=$(mktemp -d)
trap "rm -rf '$tempdir'" EXIT  # Clean up on exit

# Create m3u playlist
m3u="$tempdir/playlist.m3u"
> "$m3u"

# Generate announcements and add to playlist
j=0
for file in "${play_sequence[@]}"; do
  name="${file##*/}"
  name="${name%.*}"
  announce_wav="$tempdir/announce_$j.wav"
  echo "$name" | text2wave -o "$announce_wav"
  echo "$announce_wav" >> "$m3u"
  echo "$file" >> "$m3u"
  ((j++))
done

# Create ezstream config
config="$tempdir/config.xml"
protocol=$(if [ $IS_ICECAST -eq 1 ]; then echo "HTTP"; else echo "ICY"; fi)
cat <<EOF > "$config"
<ezstream>
  <servers>
    <server>
      <hostname>$HOST</hostname>
      <password>$PASSWORD</password>
      <protocol>$protocol</protocol>
      <port>$PORT</port>
    </server>
  </servers>
  <streams>
    <stream>
      <mountpoint>$MOUNTPOINT</mountpoint>
      <format>Mp3</format>
    </stream>
  </streams>
  <intakes>
    <intake>
      <filename>$m3u</filename>
      <shuffle>0</shuffle>
      <stream_once>0</stream_once>
    </intake>
  </intakes>
  <decoders>
    <decoder>
      <format>Mp3</format>
      <extensions>.mp3</extensions>
      <program>mpg123 --stereo --rate 44100 --stdout @T@</program>
    </decoder>
    <decoder>
      <format>Wav</format>
      <extensions>.wav</extensions>
      <program>sox -t wav @T@ -t raw --rate 44100 --channels 2 --encoding signed-integer --bits 16 --endian little -</program>
    </decoder>
  </decoders>
  <encoders>
    <encoder>
      <format>Mp3</format>
      <program>lame -r -m s -s 44.1 -b 96 -q 9 --lowpass 16 - -</program>
    </encoder>
  </encoders>
</ezstream>
EOF

# Run ezstream
ezstream -c "$config"