#!/usr/bin/env bash
set -eu

version=3.4.3
arch="$(uname -m)"

case $arch in
    "x86_64")
        binary="shfmt_v${version}_linux_amd64"
        sha256=713ef49db9a60a00636814a507da851b58da6b4b98a3627188fba0a61b60f9a8
        ;;

    "aarch64")
        binary="shfmt_v${version}_linux_arm64"
        sha256=b4f5d7b53012a1a7fdac5df8f13d829d82bc7ace53da4a09c532ac562589b106
        ;;
esac

check_version() {
    out="$(shfmt --version 2>/dev/null)" && [ "$out" = "v$version" ]
}

if ! check_version; then
    tmpdir="$(mktemp -d)"
    trap 'rm -r "$tmpdir"' EXIT
    cd "$tmpdir"
    curl -fLO "https://github.com/mvdan/sh/releases/download/v$version/$binary"
    sha256sum -c <<<"$sha256 $binary"
    chmod +x "$binary"
    mv "$binary" /usr/local/bin/shfmt
    check_version
fi
