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

KUBECTL_VERSION="${KUBECTL_VERSION:-v1.36.1}"
KUBECTL_DEST="${KUBECTL_DEST:-bin/kubectl}"
CURL="${CURL:-curl}"
KUBECTL_DOWNLOAD_SHA256="${KUBECTL_DOWNLOAD_SHA256:-}"

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

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

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 "$KUBECTL_DOWNLOAD_SHA256" ]]; then
	case "${KUBECTL_VERSION}/${os}-${arch}" in
	v1.36.1/linux-amd64) KUBECTL_DOWNLOAD_SHA256=629d3f410e09bf49b64ae7079f7f0bda1191efed311f7d37fdbab0ad5b0ec2b7 ;;
	v1.36.1/linux-arm64) KUBECTL_DOWNLOAD_SHA256=59f7ee8e477fae658447607dc3c8790ac17a1b016c01c622c12070e969e2d4e7 ;;
	v1.36.1/darwin-amd64) KUBECTL_DOWNLOAD_SHA256=b4973e90ebb00537d735b63d6f8293c1959156e6ff435f6a43c08aeaa1a2e7d7 ;;
	v1.36.1/darwin-arm64) KUBECTL_DOWNLOAD_SHA256=9092778abaef3079449da4cd70ded0e4be112480c93efcdeace3155968d1d133 ;;
	*) fail "no pinned checksum for ${KUBECTL_VERSION}/${os}-${arch}; set KUBECTL_DOWNLOAD_SHA256" ;;
	esac
fi

temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/capacity-planner-kubectl.XXXXXX")"
trap 'rm -rf "$temp_dir"' EXIT
download="${temp_dir}/kubectl"
url="https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/${os}/${arch}/kubectl"

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

mkdir -p "$(dirname "$KUBECTL_DEST")"
install -m 0755 "$download" "$KUBECTL_DEST"
echo "install-kubectl: installed ${KUBECTL_VERSION} at ${KUBECTL_DEST}"
