#!/bin/bash
echo Downloading missing assets...

server="https://game-assets.fer.al"
if [ "$4" != "" ]; then
    server="$4"
fi

i=0
if [ ! -d "$2" ]; then mkdir -p "$2" ; fi

while read line; do
    file="$(basename "$line")"
    if [ "$file" == "DefID.Timestamp.unity3d" ]; then continue ; fi
    i=$((i+1))
done <"$1"
filecount=$i
i=0

failed=0
while read line; do
    file="$(basename "$line")"
    if [ "$file" == "DefID.Timestamp.unity3d" ]; then continue ; fi
    i=$((i+1))
    if [ -f "$2/$file" ]; then
        echo "[$i/$filecount] Skipped: $file"
    else
        if [ -f "$2/$file.tmp" ]; then rm "$2/$file.tmp" ; fi
        line="${line//https:\/\/game-assets.fer.al/$server}"
        curl "${line// /%20}" --output "$2/$file.tmp" -skf
        mv "$2/$file.tmp" "$2/$file"
        if [ "$?" == 0 ]; then
            echo "[$i/$filecount] Downloaded $file"
        else
            echo "[$i/$filecount] Failed to download $file"
            failed=$((failed+1))
        fi
    fi
done <"$1"
echo $failed failed items in $3 download.
