#!/bin/bash
m3u=$1
if [ "$1" = "" ]; then
   echo "Please offer m3u playlist to convert."
   exit
fi
declare -a name
declare -a stream
name=($(cat $m3u | grep \#EXTINF | awk -F"," '{print $2}' | sed 's/ /_/g' | sed 's/\//-/g'))
stream=($(cat $m3u | grep http | awk -F"/" '{print "http://127.0.0.1:3000/"$4"/"$5}'))
name_count=${#name[*]}
stream_count=${#stream[*]}
if [ $name_count -eq $stream_count ]; then
   echo "We do have ${name_count} station names and ${stream_count} stream addresses, good." 
   echo "Start conversation into *.vdrs files."
else
   echo "Number of station names (${name_count}) do not match with number of stream addresse (${stream_count})."
   echo "Please check source."
   exit
fi
I=$name_count
while [ $I -ne 0 ]
do
   case $I in
   [0-9][0-9])
      K=0$I
      I=$(($I - 1))
      ;;
   [0-9])
      K=00$I
      I=$(($I - 1))
      ;;
   *)
      I=$(($I - 1))
      ;;
   esac
   echo "URL=${stream[${I}]}" > "${K}-${name[${I}]}.vdrs"
done
echo "Finished conversation."
exit
