#!/bin/bash

download_ioncube_loaders() {
	local arch=$1    # x86-64 or aarch64
        local url="https://downloads.ioncube.com/loader_downloads/ioncube_loaders_lin_${arch}.tar.gz"
        local file="${url##*/}"

	local tmp_file
	if ! tmp_file=$(mktemp --suffix=.ioncube_loaders); then
		echo "failed to create temp file" 1>&2
		return 1
	fi
	(
		trap 'rm -f "${tmp_file}"' EXIT
		if ! curl --silent --location --fail --output "${tmp_file}" "${url}"; then
			echo "failed to download from '${url}' to file '${tmp_file}'"
			return 1
		fi

		local version
		version=$(tar --extract --file "${tmp_file}" --to-stdout ioncube/ioncube_loader_lin_8.2.so | strings | grep '^version: [0-9.]\+' | cut -d ' ' -f 2)
		if [ -z "${version}" ]; then
			echo "failed to detect latest file version"
			return 1
		fi
		local dir="ioncube_${version}"
		mkdir -p "${dir}"

		local tmp_checksum=$(md5sum "${tmp_file}" | cut -d ' ' -f 1)

		if [ -f "${dir}/${file}" ]; then
			if [ "${tmp_checksum}" != "$(md5sum "${dir}/${file}" | cut -d ' ' -f 1)" ]; then
				echo "[failed] checksum missmatch for '${dir}/${file}'"
				return 1
			fi
			echo "[cached] [${tmp_checksum}] ${dir}/${file}"
		else
			chmod 644 "${tmp_file}"
			mv -f "${tmp_file}" "${dir}/${file}"
			echo "[added ] [${tmp_checksum}] ${dir}/${file}"
		fi
	)
}

download_ioncube_loaders x86-64
download_ioncube_loaders aarch64
