#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
TOOLS="$ROOT/.tools/bin"
mkdir -p "$TOOLS"

KUBECTL_VERSION=v1.36.2
HELM_VERSION=v4.2.3
KIND_VERSION=v0.32.0

case "$(uname -m)" in
  x86_64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

verified_download() {
  url=$1
  checksum_url=$2
  destination=$3
  archive=$4
  temp="${destination}.download"
  checksum="${temp}.sha256"

  curl --fail --location --silent --show-error "$url" --output "$temp"
  curl --fail --location --silent --show-error "$checksum_url" --output "$checksum"

  expected=$(awk '{print $1}' "$checksum")
  actual=$(sha256sum "$temp" | awk '{print $1}')
  if [ "$expected" != "$actual" ]; then
    echo "Checksum mismatch for $url" >&2
    exit 1
  fi

  if [ "$archive" = "tar" ]; then
    directory="${temp}.dir"
    mkdir -p "$directory"
    tar -xzf "$temp" -C "$directory"
    install -m 0755 "$directory/linux-${ARCH}/helm" "$destination"
  else
    install -m 0755 "$temp" "$destination"
  fi
}

if [ ! -x "$TOOLS/kubectl" ]; then
  verified_download \
    "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/${ARCH}/kubectl" \
    "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/${ARCH}/kubectl.sha256" \
    "$TOOLS/kubectl" binary
fi

if [ ! -x "$TOOLS/kind" ]; then
  verified_download \
    "https://kind.sigs.k8s.io/dl/${KIND_VERSION}/kind-linux-${ARCH}" \
    "https://kind.sigs.k8s.io/dl/${KIND_VERSION}/kind-linux-${ARCH}.sha256sum" \
    "$TOOLS/kind" binary
fi

if [ ! -x "$TOOLS/helm" ]; then
  verified_download \
    "https://get.helm.sh/helm-${HELM_VERSION}-linux-${ARCH}.tar.gz" \
    "https://get.helm.sh/helm-${HELM_VERSION}-linux-${ARCH}.tar.gz.sha256sum" \
    "$TOOLS/helm" tar
fi

"$TOOLS/kubectl" version --client
"$TOOLS/kind" version
"$TOOLS/helm" version
