#!/usr/bin/env bash

# Copyright 2026 PingCAP, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail

BUILDKIT_VERSION="${BUILDKIT_VERSION:-v0.31.2}"
BUILDCTL_DEST="${BUILDCTL_DEST:-bin/buildctl}"
CURL="${CURL:-curl}"
BUILDCTL_DOWNLOAD_SHA256="${BUILDCTL_DOWNLOAD_SHA256:-}"

fail() {
	echo "install-buildctl: $*" >&2
	exit 1
}

command -v "$CURL" >/dev/null 2>&1 || fail "curl is not executable: ${CURL}"
command -v tar >/dev/null 2>&1 || fail "tar is not executable"

case "$(uname -s)" in
Linux) os=linux ;;
Darwin) os=darwin ;;
*) fail "unsupported operating system: $(uname -s)" ;;
esac

case "$(uname -m)" in
x86_64 | amd64) arch=amd64 ;;
aarch64 | arm64) arch=arm64 ;;
*) fail "unsupported architecture: $(uname -m)" ;;
esac

if [[ -z "$BUILDCTL_DOWNLOAD_SHA256" ]]; then
	case "${BUILDKIT_VERSION}/${os}-${arch}" in
	v0.31.2/linux-amd64) BUILDCTL_DOWNLOAD_SHA256=fbabdb72433a35f5bb646e4cd424bf8567e5d055710cf55840f7af2020640791 ;;
	v0.31.2/linux-arm64) BUILDCTL_DOWNLOAD_SHA256=41fba1eed480376934fa4c8177ddd7021036b5168a0eb8e7ab5eccdf75d47a05 ;;
	v0.31.2/darwin-amd64) BUILDCTL_DOWNLOAD_SHA256=c99fd17d2f37a0bf025b26601fea6fdcf7831ec9858a1fa63bcacb2e06441a2d ;;
	v0.31.2/darwin-arm64) BUILDCTL_DOWNLOAD_SHA256=c386267eab33e79f4a0cb6a59230b71cddbacb5bf9e93fdf2d2682f2b4fa1a18 ;;
	*) fail "no pinned checksum for ${BUILDKIT_VERSION}/${os}-${arch}; set BUILDCTL_DOWNLOAD_SHA256" ;;
	esac
fi

temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/capacity-planner-buildctl.XXXXXX")"
trap 'rm -rf "$temp_dir"' EXIT
archive="${temp_dir}/buildkit.tar.gz"
url="https://github.com/moby/buildkit/releases/download/${BUILDKIT_VERSION}/buildkit-${BUILDKIT_VERSION}.${os}-${arch}.tar.gz"

echo "install-buildctl: downloading ${url}"
"$CURL" -fsSL --retry 3 -o "$archive" "$url"
if command -v sha256sum >/dev/null 2>&1; then
	actual_sha256="$(sha256sum "$archive" | awk '{print $1}')"
elif command -v shasum >/dev/null 2>&1; then
	actual_sha256="$(shasum -a 256 "$archive" | awk '{print $1}')"
else
	fail "sha256sum or shasum is required"
fi
[[ "$actual_sha256" == "$BUILDCTL_DOWNLOAD_SHA256" ]] ||
	fail "checksum mismatch: got ${actual_sha256}, want ${BUILDCTL_DOWNLOAD_SHA256}"

tar -xOzf "$archive" bin/buildctl >"${temp_dir}/buildctl"
chmod 0755 "${temp_dir}/buildctl"
mkdir -p "$(dirname "$BUILDCTL_DEST")"
install -m 0755 "${temp_dir}/buildctl" "$BUILDCTL_DEST"
echo "install-buildctl: installed ${BUILDKIT_VERSION} at ${BUILDCTL_DEST}"
