#!/bin/dash

# JakeSFR: This script updates playlist luac scripts for VLC

PLAYLIST_DIR_URL='https://github.com/videolan/vlc/tree/master/share/lua/playlist'
DOWNLOAD_URL='https://raw.githubusercontent.com/videolan/vlc/master/share/lua/playlist'
DESTDIR="/usr/lib64/vlc/lua/playlist"
TMPFILE="/tmp/vlc_lua.$USER.$$"

trap 'rm -f "$TMPFILE"; exit' 0 INT HUP TERM

die () {
	echo "$@"
	echo "Aborted!"
	exit 1
}

if [ $(id -u) -ne 0 ]; then
	die "Must run as root."
fi

if ! wget -q --spider "$PLAYLIST_DIR_URL"; then
	die "Can't connect to ${PLAYLIST_DIR_URL}"
fi

SCRIPTS=$(wget -qO - "$PLAYLIST_DIR_URL" | sed -n 's/.*title="\(.*.lua\)" .*/\1/p')

if [ -z "$SCRIPTS" ]; then
	die "Failed to parse scripts names at $PLAYLIST_DIR_URL"
fi

for p in $(echo $SCRIPTS); do

	echo -n "Updating '${p}c'..."
	
	if ! wget -q -O "$TMPFILE" "${DOWNLOAD_URL}/${p}"; then
		echo "failed to download the script!"
		continue
	fi
	
	case "$p" in
		twitch.lua)	# twitch.lua stopped working at some point and nobody updated it yet
			# If 'allow_audio_only=true', VLC plays audio only, so let's change it to 'false'.
			# It may break audio-only streams/videos, but I wasn't able to find any to test.
			sed -i 's/allow_audio_only=true/allow_audio_only=false/g' "$TMPFILE"
			;;
	esac

	if ! luac -o "${DESTDIR}/${p}c" "$TMPFILE" 2>/dev/null; then
		echo "failed to compile the script!"
		continue
	fi
	
	echo "success!"

done

echo "Done."
