#!/bin/bash -e

echo "Welcome to the Skylords Reborn updating script. It will check your game's files and bring them up to date."
echo "It is recommended to run this script everytime before you want to play the game."

cd "$(dirname "$0")"

missing_deps=""
for dep in tr wc sed curl md5sum jq; do
    if ! which $dep > /dev/null; then
        missing_deps="$missing_deps $dep"
    fi
done
if [ x"$missing_deps" != x"" ]; then
    echo "The following dependencies of this script are missing: $missing_deps"
    exit 1
fi

WEBSITE_URL="http://download.skylords.eu/"

# returns list of all files, one per line with "update/" prefix, followed by ; and md5 sum
echo "Fetching update list..."
update_json="$(curl "$WEBSITE_URL/manifest-live-v2.json")"
update_json="$(echo "$update_json" | sed 's|\\|/|g')"

base_path="$(echo "$update_json" | jq -r '.basePath // "update"')"

update_list="$(echo "$update_json" | jq -r '.files[] | "\(.path);\(.hash)"')"

# now download them one by one from website if md5 does not match
i=0
n="$(echo "$update_list" | wc -l)"

echo "$update_list" | while IFS= read -r x; do
    i=$((i+1))
    file="$(echo "$x" | cut -d';' -f1)"
    new_md5="$(echo "$x" | cut -d';' -f2)"

    echo "$file"

    local_md5="$(md5sum "$file" 2>/dev/null | cut -d' ' -f1)" || true
    if [ x"$local_md5" != x"$new_md5" ]; then
        file_url="$WEBSITE_URL/$base_path/$file"
        file_url="${file_url// /%20}"
        echo "[$i/$n] Fetching $file_url ..."
        curl --create-dirs -o "$file" "$file_url"
    else
        echo "[$i/$n] $file is up to date."
    fi
done

echo "The game files have successfully been updated."
echo "You can now use wine, proton or another compatibility tool of your choice to start the game."
echo "For further instructions or if you need help, check https://forum.skylords.eu/ or the official Skylords Reborn Discord server."
