#! /usr/bin/env bash
# Unvanquished 0.51.1 Linux patcher
# CC0 1.0 2020 Unvanquished Developers
program_dir="$(dirname "${BASH_SOURCE[0]}")"
install_dir="${XDG_DATA_HOME:-${HOME}/.local/share}/unvanquished/base"

command -v sha512sum >/dev/null || exit 1
command -v dd >/dev/null || exit 1

get () {
 case "${1}" in
 daemon_sum)      printf '1f9a838b690e1775e975a7aef1c67412710995c7d1f9e2a350c56fb981d0234f4dc95458294b58aa4c4dd75a0e96f0be3cd645cf31209a5a4bc92a6a35823786' ;;
 daemonded_sum)   printf '7f812b5ce1e0e1241cb37f1f1878b94184ba2faf220ea49027f31b0f38cd5f5f768c1aa44d3b483e7f8902cefd1d7af39136d880c980b538741aa7c0785f7644' ;;
 daemon_patch)    printf '\x8b\x74\x24\x20\x48\x31\xc0\x85\xf6\x0f\x94\xc0\xeb\x3f' ;;
 daemonded_patch) printf '\x8b\x74\x24\x20\x48\x31\xc0\x85\xf6\x0f\x94\xc0\xeb\x3f' ;;
 daemon_seek)     printf '2186551' ;;
 daemonded_seek)  printf '738855' ;;
 esac
}

if [ -z "${1}" ]; then exit 1
elif [ -f "${1}" ]; then binary_file="$(realpath "${1}")"
elif [ -f "${program_dir}/${1}" ]; then binary_file="${program_dir}/${1}"
elif [ -f "${install_dir}/${1}" ]; then binary_file="${install_dir}/${1}"
else exit 1
fi; shift

binary_sum="$(sha512sum -- "${binary_file}" | cut -f1 -d' ')"
for binary_name in daemon daemonded; do if [ "$(get "${binary_name}_sum")" = "${binary_sum}" ]; then
 patch_data="$(get "${binary_name}_patch")"
 patch_seek="$(get "${binary_name}_seek")"
 temp_file="$(mktemp "${binary_file}.patched.XXXXXX")"
 if [ ${?} = 0 ]; then cp -a -- "${binary_file}" "${temp_file}" \
 && printf "${patch_data}" | dd of="${temp_file}" bs=1 seek="${patch_seek}" count="${#patch_data}" conv=notrunc \
 && "${temp_file}" "${@}"
 rm -- "${temp_file}"; fi; exit
fi; done; exit 1
