#!/usr/bin/env bash set -euo pipefail BASE_URL="https://cli.typedgate.com" BINARY_NAME="typedgate" TMP_DIR="" cleanup() { if [[ -n "${TMP_DIR}" && -d "${TMP_DIR}" ]]; then rm -rf "${TMP_DIR}" fi } verify_sha256() { local sums_file="$1" target_file="$2" expected actual expected=$(tr -d '\r' < "${sums_file}" | awk -v f="${target_file}" ' NF == 2 { sub(/^\*/, "", $2) sub(/^\.\//, "", $2) if ($2 == f) { print $1; exit } } ') if [[ ! "${expected}" =~ ^[0-9a-fA-F]{64}$ ]]; then printf 'Error: Valid 64-char SHA-256 entry for %s not found.\n' "${target_file}" >&2 return 1 fi printf '%s %s\n' "${expected}" "${target_file}" > "${TMP_DIR}/SINGLE.sha256" if command -v sha256sum >/dev/null 2>&1; then (cd "${TMP_DIR}" && sha256sum -c SINGLE.sha256 >/dev/null) elif command -v shasum >/dev/null 2>&1; then (cd "${TMP_DIR}" && shasum -a 256 -c SINGLE.sha256 >/dev/null) elif command -v openssl >/dev/null 2>&1; then actual=$(openssl sha256 "${TMP_DIR}/${target_file}" | awk '{print $NF}') if [[ "$(printf '%s' "${actual}" | tr '[:upper:]' '[:lower:]')" != "$(printf '%s' "${expected}" | tr '[:upper:]' '[:lower:]')" ]]; then printf 'Error: OpenSSL SHA-256 mismatch for %s.\n' "${target_file}" >&2 return 1 fi else printf 'Error: No SHA-256 verifier (sha256sum, shasum, openssl) found.\n' >&2 return 1 fi } main() { local os target_dir TMP_DIR="$(mktemp -d)" trap cleanup EXIT os="$(uname -s)" case "${os}" in Linux|Darwin) ;; *) printf 'Error: Unsupported OS (%s).\n' "${os}" >&2; exit 1 ;; esac curl --proto '=https' --tlsv1.2 -fsSL "${BASE_URL}/${BINARY_NAME}" -o "${TMP_DIR}/${BINARY_NAME}" curl --proto '=https' --tlsv1.2 -fsSL "${BASE_URL}/SHA256SUMS" -o "${TMP_DIR}/SHA256SUMS" verify_sha256 "${TMP_DIR}/SHA256SUMS" "${BINARY_NAME}" chmod 755 "${TMP_DIR}/${BINARY_NAME}" if [[ -w "/usr/local/bin" ]]; then target_dir="/usr/local/bin" elif [[ -n "${HOME:-}" ]]; then target_dir="${HOME}/.local/bin" mkdir -p "${target_dir}" else printf 'Error: /usr/local/bin is not writable and HOME is unset.\n' >&2 exit 78 fi mv "${TMP_DIR}/${BINARY_NAME}" "${target_dir}/${BINARY_NAME}" printf 'Installed %s to %s/%s\n' "${BINARY_NAME}" "${target_dir}" "${BINARY_NAME}" } main "$@"