#!/bin/bash -e

echo "Welcome to the Skylords Reborn installing script. It will download the game's files to the current directory."

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..."
install_json="$(curl "$WEBSITE_URL/manifest-install-v2.json")"
install_json="$(echo "$install_json" | sed 's|\\|/|g')"

base_path="$(echo "$install_json" | jq -r '.basePath // "install"')"

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

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

echo "$install_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 has successfully been installed. Now, please run the script skylords-upd.sh to update your game files."
echo "You might need to grant yourself the permission to execute the script first by running the command"
echo "chmod u+x skylords-upd.sh"
