#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=scripts/cluster/common.sh
source "$script_dir/common.sh"

load_cluster_env
require_commands curl shasum tar

# K3s v1.36.2 embeds etcd 3.6.12. The closest upstream release utility is
# 3.6.11 and uses the same v3 snapshot format.
etcd_version=3.6.11
etcd_archive=etcd-v"$etcd_version"-linux-amd64.tar.gz
etcd_archive_sha256=8756f7a4eaf921668a83de0bf13c0f65cae9186a165696e3ae8396afe6f557ed
working_directory=$(mktemp -d "$cluster_root/.local-secrets/cluster/etcdutl.XXXXXX")
trap '[[ $working_directory == "$cluster_root"/.local-secrets/cluster/etcdutl.* ]] && rm -rf -- "$working_directory"' \
  EXIT HUP INT TERM

curl -fsSL \
  "https://github.com/etcd-io/etcd/releases/download/v${etcd_version}/${etcd_archive}" \
  -o "$working_directory/$etcd_archive"
actual_sha256=$(shasum -a 256 "$working_directory/$etcd_archive" | awk '{print $1}')
[[ $actual_sha256 == "$etcd_archive_sha256" ]] || {
  echo 'etcd release archive checksum mismatch' >&2
  exit 1
}
archive_member=etcd-v"$etcd_version"-linux-amd64/etcdutl
tar -tzf "$working_directory/$etcd_archive" | grep -qx "$archive_member"
tar -xzf "$working_directory/$etcd_archive" -C "$working_directory" "$archive_member"
etcdutl_binary="$working_directory/$archive_member"

for host in "$CLUSTER_NINGBO_HOST" "$CLUSTER_HONGKONG_HOST" "$CLUSTER_LOS_ANGELES_HOST"; do
  cluster_scp "$etcdutl_binary" "$host:/root/etcdutl"
  cluster_ssh "$host" bash -s -- "$etcd_version" <<'REMOTE'
set -euo pipefail
etcd_version=$1
install -m 0755 /root/etcdutl /usr/local/bin/etcdutl
unlink /root/etcdutl
etcdutl version | grep -q "etcdutl version: ${etcd_version}"
REMOTE
done

echo "etcdutl_install=PASS version=$etcd_version nodes=3 sha256=$etcd_archive_sha256"
