#!/bin/bash

# Author: Raspbeguy

##### Parameters to check
URL_PREFIX=https://mylittlekaraoke.com/store/webinst
WORK_DIR=. # change me (if relative path, will be canonized later)
APPLICATION_DIR=./app # where the .mlu will be extracted
VERSION_FILE=./songs/version.txt # change me
##### End of parameters

WORK_DIR=$(readlink -f $WORK_DIR)
APPLICATION_DIR=$(readlink -f $APPLICATION_DIR)
VERSION_FILE=$(readlink -f $VERSION_FILE)
KERNEL=$(uname -s)

case "$KERNEL" in
	Linux)  
		OS="linux"
		;;
	Darwin) 
		OS="mac"
		;;
	*)      
		echo "I wasn't expecting that kernel. Buck it."
		exit 1
		;;
esac

WEBINST=$(wget -qO -  $URL_PREFIX/$OS.webinst)

if [ $? -ne 0 ]
then
	echo "ERROR while trying to get download file" >&2
	exit 1
fi

VERSION=$(cat $VERSION_FILE)
if [ "$VERSION" == "5.0 Final" ]
then
	to_remove=$(echo "$WEBINST" | grep -A1 "AC3")
	if [ "$to_remove" != "" ]
	then
		WEBINST=$(echo "$WEBINST" | grep -v "$to_remove")
	fi
fi


if [ "$VERSION" == "6.0 Final" ]
then
	echo "This script can't update past MLK_SIM4, visit mylittlekaraoke.com for update"
	exit 1
fi


LIST=$(echo "$WEBINST" | awk 'NR % 2 == 1')
SIZES=$(echo "$WEBINST" | awk 'NR % 2 == 0')

mkdir -p $WORK_DIR/{temp,songs,themes}

cd $WORK_DIR/temp

while read url; do
	file=$(basename $url)
	if [ -f $file ]
	then
		real_size=$(stat -c%s "$file")
	else
		real_size=0
	fi
	expected_size=$(echo "$SIZES" | head -1)
	SIZES=$(echo "$SIZES" | tail -n +2)
	while [ $real_size -ne $expected_size ]
	do
		echo "Downloading $url"
		echo "Expected size:   $expected_size"
		curl -O $url --progress-bar
		real_size=$(stat -c%s "$file")
		echo "Downloaded size: $real_size"
	done
done <<< "$LIST"

for file in $WORK_DIR/temp/*
do
	case "$file" in
		*.mlu)
			tar -xvf $file -C $APPLICATION_DIR
			;;
		*.mlk)
			tar -xvf $file -C $WORK_DIR/songs
			;;
		*.mlt)
			tar -xvf $file -C $WORK_DIR/themes
			;;
		*)
			echo "$file: I don't know this Pokemon." >&2
			;;
	esac
done

rm -rf $WORK_DIR/songs/Fixes #derp
rm -rf $WORK_DIR/temp
