#!/bin/bash

download_cwaf_client() {
	local url="$1"
	local tmp_file

	if ! tmp_file=$(mktemp --suffix=.cwaf_client); 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
	
		version=$(grep -a -m 1 -P -o -e '(?<=Comodo WAF Client Installer v)[0-9.]+' "${tmp_file}")
		if [ -z "${version}" ]; then
			echo "failed to detect latest file version"
			return 1
		fi
	
		local tmp_checksum=$(md5sum "${tmp_file}" | cut -d ' ' -f 1)
		local file="cwaf_client_install_${version}.sh"
		if [ -f "${file}" ]; then
			if [ "${tmp_checksum}" != "$(md5sum "${file}" | cut -d ' ' -f 1)" ]; then
				echo "[failed] checksum missmatch for '${file}'"
				return 1
			fi
			echo "[cached] [${tmp_checksum}] ${file}"
		else
			chmod 644 "${tmp_file}"
			mv -f "${tmp_file}" "${file}"
			echo "[added ] [${tmp_checksum}] ${file}"
		fi
	)
}

download_cwaf_client https://waf.comodo.com/cpanel/cwaf_client_install.sh
