if [ "$#" -lt 3 -o "$#" -gt 3 ]; then
    echo "Usage: $0 URL DESTINATION SHA256SUM"
    exit 1
fi

source scripts/lib.sh

URL="$1"
DESTINATION="$2"
SHA256SUM="$3"

if command -v wget >/dev/null 2>&1; then
    USE_WGET=yes
else
    if command -v curl >/dev/null 2>&1; then
        USE_WGET=no
    else
        echo "Found neither wget nor curl. Aborting."
        exit 1
    fi
fi

if [ ! -d .download_cache ]; then
    echo "Cache directory missing."
    create_directory .download_cache
fi

#TODO: keep track of which cached file is downloaded to which destination
#TODO: when downloading a file with a new hash to the same destination, mark the old one as no longer in use
#TODO: if there is an even older one for the same download path, delete it
#TODO: remove cache maintenance from clean_dependencies

if [ -f ".download_cache/$SHA256SUM" ]; then
    if check_sha256 ".download_cache/$SHA256SUM" "$SHA256SUM"; then
        echo "Using locally cached file for $DESTINATION"
        cp ".download_cache/$SHA256SUM" "$DESTINATION"
        exit 0
    else
        echo "Locally cached file for $DESTINATION is corrupted."
        rm ".download_cache/$SHA256SUM"
        $0 "$URL" "$DESTINATION" "$SHA256SUM"
        exit $?
    fi
else
    echo -n "Downloading $URL to $DESTINATION... "
    if [ $USE_WGET = yes ]; then
        wget -O ".download_cache/$SHA256SUM" "$URL" >/dev/null 2>&1
    else
        curl -L "$URL" --output ".download_cache/$SHA256SUM" >/dev/null 2>&1
    fi
    if check_sha256 ".download_cache/$SHA256SUM" "$SHA256SUM"; then
        cp ".download_cache/$SHA256SUM" "$DESTINATION"
        echo "done."
        exit 0
    else
        echo "error."
        echo "Checksum verification failed. Your download is either corrupted or the file has been altered. Removing file."
        rm ".download_cache/$SHA256SUM"
        exit 1
    fi
fi
