#!/bin/sh
#
# This script executes clang-format in the following order:
#
# 1. If environment variable CLANG_FORMAT is set, execute $CLANG_FORMAT.
# 2. Otherwise, if <ccache-top-dir>/misc/.clang-format-exe exists, execute that
#    program.
# 3. Otherwise, download a statically linked clang-format executable, verify its
#    integrity, place it in <ccache-top-dir>/misc/.clang-format-exe and execute
#    it.

set -eu

if [ -n "${CLANG_FORMAT:-}" ]; then
    exec "$CLANG_FORMAT" "$@"
fi

misc_dir="$(dirname "$0")"
clang_format_exe="${misc_dir}/.clang-format-exe"
clang_format_version=18
clang_format_release=master-609f1513
url_prefix="https://github.com/muttleyxd/clang-tools-static-binaries/releases/download/${clang_format_release}/clang-format-${clang_format_version}_"

if [ ! -x "$clang_format_exe" ]; then
    case "$(uname -s | tr '[:upper:]' '[:lower:]')" in
        *mingw*|*cygwin*|*msys*)
            url_suffix=windows-amd64.exe
            checksum=d8c788f0d983177ae2ebcac6cb32d0e9bd79f93bae5aab5197b1d5998be4f90b
            ;;
        *darwin*)
            url_suffix=macosx-amd64
            checksum=de1a6affc3253af8cf48130d2940375b284025bedbb2b812d55e85cfdff69e83
            ;;
        *linux*)
            url_suffix=linux-amd64
            checksum=2a6cd633f85e96a32f68cca3f1ac2ef63c677cae0f2b2a7f2a0c3f81a36a2353
            ;;
        *)
            echo "Error: Please set CLANG_FORMAT to clang-format version $clang_format_version" >&2
            exit 1
            ;;
    esac

    url="$url_prefix$url_suffix"

    if command -v wget >/dev/null; then
        wget -qO "$clang_format_exe.tmp" "$url"
    elif command -v curl >/dev/null; then
        curl -so "$clang_format_exe.tmp" -L --retry 20 "$url"
    else
        echo "Error: Neither wget nor curl found" >&2
        exit 1
    fi

    if ! command -v sha256sum >/dev/null; then
        echo "Warning: sha256sum not found, not verifying clang-format integrity" >&2
    elif ! echo "$checksum $clang_format_exe.tmp" | sha256sum --status -c -; then
        echo "Error: Bad checksum of downloaded clang-format: expected ${checksum}, actual $(sha256sum ${clang_format_exe}.tmp | awk '{print $1}')" >&2
        exit 1
    fi

    chmod +x "$clang_format_exe.tmp"
    mv "$clang_format_exe.tmp" "$clang_format_exe"
fi

exec "$clang_format_exe" "$@"
