#!/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

top_dir="$(dirname "$0")"
clang_format_exe="$top_dir/.clang-format-exe"
clang_format_version=11
clang_format_release=master-1d7ec53d
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=7167f201acbd8ff06a7327d14db0d8a169393384bbc42873bb8277b788cc4469
            ;;
        *darwin*)
            url_suffix=macosx-amd64
            checksum=0cab857e66aa9ed9ea00eee3c94bfc91a2d72ab440327e15784852cf94b1814b
            ;;
        *linux*)
            url_suffix=linux-amd64
            checksum=a9d76e3275823ea308bc2e4d2a6e3cc693f38c29d891f1d74cb0e1553e698dea
            ;;
        *)
            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" >&2
        exit 1
    fi

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

exec "$clang_format_exe" "$@"
