#!/bin/bash

set -e

download_with_cache() {
	local url=$1
	local file="${url##*/}"
	local checksum
	if ! checksum=$(curl --silent --fail "${url}.md5" | cut -d ' ' -f 1); then
		echo "[failed] fetching checksum '${url}.md5'"
		return
	fi

	if [ -e "${file}" ]; then
		if [ "${checksum}" = "$(md5sum "${file}" | cut -d ' ' -f 1)" ]; then
			echo "[cached] [${checksum}] ${file}"
			return
		else
			echo "[failed] checksum missmatch for '${file}'"
			return
		fi
	fi

	if ! curl --silent --fail --output "${file}.tmp" "${url}"; then
		rm -f "${file}.tmp"
		echo "[failed] fetching file '${url}'"
		return
	fi
	if [ "${checksum}" = "$(md5sum "${file}.tmp" | cut -d ' ' -f 1)" ]; then
		mv "${file}.tmp" "${file}"
		echo "[added ] [${checksum}] ${file}"
	else
		rm -f "${file}.tmp" 
		echo "[failed] checksum missmatch after download for '${file}'"
	fi
}

v=8.0.36
download_with_cache "https://cdn.mysql.com/Downloads/MySQL-${v%.*}/mysql-${v}-linux-glibc2.17-x86_64-minimal.tar.xz"
download_with_cache "https://cdn.mysql.com/Downloads/MySQL-${v%.*}/mysql-${v}-linux-glibc2.17-aarch64-minimal.tar.xz"
download_with_cache "https://cdn.mysql.com/Downloads/MySQL-${v%.*}/mysql-${v}.tar.gz"

v=5.7.44
download_with_cache "https://cdn.mysql.com/Downloads/MySQL-${v%.*}/mysql-${v}-linux-glibc2.12-x86_64.tar.gz"
download_with_cache "https://cdn.mysql.com/Downloads/MySQL-${v%.*}/mysql-${v}.tar.gz"
