#!/bin/bash

# WIFLY VARIABLES

SSID=PBE
#SSID=SERVER_WLAN
ROUTE=$1
DEST_IP=10.0.2.100
#DEST_IP=192.168.1.1
PORT=80
WIFLY=/dev/ttyUSB0
SERIAL_OPTS="ispeed $SPEED ospeed $SPEED"
SPEED=9600
STARTWORD="Content-Type: application/vnd.apple.mpegurl"
ENDWORD="*CLOS*"
WRITE=0

# PARSING VARIABLES

M3U8_VALIDATED=0
SEQUENCE_FIRST=0
MAX_DURATION=-1
CURRENT_SEGMENT=0
CURRENT_LINE=1
EXTINF=0
CODECS=""
RESOLUTION=""
BANDWIDTH=""
PROGRAMID=""
EXTXSTREAM=0

# FUNCTIONS

parse()
{
	if [[ $line == "" ]];then
		((CURRENT_LINE++))
		return
	else
		if [[ $M3U8_VALIDATED -eq 0 ]]; then
			if [[ $line == "#EXTM3U" ]]; then
				M3U8_VALIDATED=1
			else
				echo "ERROR: This is not an m3u8 file!!"
				exit 1
			fi
		else
			if [[ `echo $line | head -c1` == "#" ]]; then
				if [[ `echo $line | head -c4` == "#EXT" ]]; then
					case `echo $line | cut -d':' -f 1` in
						"#EXT-X-MEDIA-SEQUENCE")
							SEQUENCE_FIRST=`echo $line | cut -d':' -f 2`;
							echo "INFO: First element to be played is: $SEQUENCE_FIRST";;
						"#EXT-X-TARGETDURATION")
							MAX_DURATION=`echo $line | cut -d':' -f 2`;
							echo "INFO: Maximum segment duration is: $MAX_DURATION";;
						"#EXTINF")
							DURATION=`echo $line | cut -d':' -f 2 | cut -d',' -f 1`
							if [[ $DURATION > $MAX_DURATION ]]; then
								echo "ERROR: Segment $CURRENT_SEGMENT on line $CURRENT_LINE is larger than EXT-X-TARGETDURATION"
								exit 1
							else
								NAME=`echo $line | cut -d':' -f 2 | cut -d',' -f 2`
								EXTINF=1
							fi;;
						"#EXT-X-STREAM-INF")
							EXTXSTREAM=1
							PROGRAMID=""
							CODECS=""
							RESOLUTION=""
							ARGUMENTS=`echo $line | cut -d':' -f 2`
							i=1
							while [[ `echo $ARGUMENTS | cut -d',' -f $i` != "" ]]; do
								PARAMETER=`echo $ARGUMENTS | cut -d',' -f $i | cut -d'=' -f 2`
								case `echo $ARGUMENTS | cut -d',' -f $i | cut -d'=' -f 1` in
									"PROGRAM-ID")
										PROGRAMID=$PARAMETER;;
									"BANDWIDTH")
										BANDWIDTH=$PARAMETER;;
									"RESOLUTION")
										RESOLUTION=$PARAMETER;;
									"CODECS")
										CODECS=$PARAMETER;;
								esac
								((i++))
							done;;
						"#EXT-X-ENDLIST")
							echo "INFO: Playlist end reached";;
					esac
				else
					echo "INFO: Comment found on line $CURRENT_LINE: \"`echo $line | cut -d'#' -f 2`\""
				fi;
			else
				if [[ $EXTINF -eq 1 ]]; then
					echo -n "SEGMENT $CURRENT_SEGMENT: \"$NAME\" - $DURATION seconds ($line)"
					EXTINF=0
					if [[ $CURRENT_SEGMENT -eq $SEQUENCE_FIRST ]]; then
						echo " (first element)"
					else
						echo ""
					fi;
					((CURRENT_SEGMENT++))
				elif [[ $EXTXSTREAM -eq 1 ]]; then
					echo "PLAYLIST: $line [PROGRAM-ID=$PROGRAMID,BANDWIDTH=$BANDWIDTH,RESOLUTION=$RESOLUTION,CODECS=$CODECS]"
                                        EXTXSTREAM=0
				else
					echo "ERROR: Unexpected string \"$line\""
					exit 1
				fi
			fi
		fi
	fi
	((CURRENT_LINE++))
}

fetch()
{
	echo -ne "set com remote GET\$$1\r" >> $WIFLY
	echo -ne "open $DEST_IP $PORT\r" >> $WIFLY

	# PARSE

	cat $WIFLY | while read line; do
		line=`echo $line | tr -d '\r' | sed 's/\*CLOS\*CMD/\*CLOS\*/g'`	# STRIP EXTRA CR AND DETECT EOF
		if [[ "$line" == "$STARTWORD" && $WRITE == 0 ]]; then
			echo "INFO: Playlist $1 START:"
			WRITE=1;
			continue;
		fi
		if [[ "$line" == "$ENDWORD" ]]; then
			echo "INFO: EOF"
			break;
		fi
		if [[ $WRITE -eq 0 ]]; then
			continue;
		else
			parse $line
		fi
	done
}

initialize()
{
	echo -n "\$\$\$" >> $WIFLY
	# IF ANY CHARACTER GETS INTO THE BUFFER 250 ms AFTER THE $$$ SEQUENCE IT WILL NOT ENTER COMMAND MODE
	sleep 0.300 # TO BE SAFE
}

if [[ -z $1 ]]; then
	echo "ERROR: Missing path"
	echo -e "\nUSAGE: $0 <RELATIVE_PATH> (i.e /playlist.m3u8)"
	exit 1
fi

# SERIAL PORT CONFIGURATION

stty -F $WIFLY $SERIAL_OPTS

# INPUT COMMANDS

initialize
echo -ne "set wlan join 1\r" >> $WIFLY
echo -ne "set wlan auth 0\r" >> $WIFLY
echo -ne "set wlan ssid $SSID\r" >> $WIFLY
echo -ne "join  $SSID\r" >> $WIFLY
sleep 5 # GIVE TIME TO THE DHCP CLIENT
echo -ne "set ip proto 18\r" >> $WIFLY
fetch $ROUTE

#cat $1 | while read line; do
#	parse $line
#done

exit 0
