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

plugin_version=1.29.1
plugin_archive=kubectl-cnpg_"$plugin_version"_linux_x86_64.tar.gz
plugin_sha256=2a550d5ee2224e5bb66b95602f8052fc50da50485f59f97b817a0c3b44b58581
working_directory=$(mktemp -d "$cluster_root/.local-secrets/cluster/cnpg-plugin.XXXXXX")
trap '[[ $working_directory == "$cluster_root"/.local-secrets/cluster/cnpg-plugin.* ]] && rm -rf -- "$working_directory"' \
  EXIT HUP INT TERM

curl -fsSL \
  "https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v${plugin_version}/${plugin_archive}" \
  -o "$working_directory/$plugin_archive"
actual_sha256=$(shasum -a 256 "$working_directory/$plugin_archive" | awk '{print $1}')
[[ $actual_sha256 == "$plugin_sha256" ]] || {
  echo 'kubectl-cnpg archive checksum mismatch' >&2
  exit 1
}
tar -tzf "$working_directory/$plugin_archive" | grep -qx kubectl-cnpg
tar -xzf "$working_directory/$plugin_archive" -C "$working_directory" kubectl-cnpg
cluster_scp "$working_directory/kubectl-cnpg" "$CLUSTER_NINGBO_HOST:/root/kubectl-cnpg"
cluster_ssh "$CLUSTER_NINGBO_HOST" bash -s -- "$plugin_version" <<'REMOTE'
set -euo pipefail
plugin_version=$1
install -m 0755 /root/kubectl-cnpg /usr/local/bin/kubectl-cnpg
unlink /root/kubectl-cnpg
k3s kubectl cnpg version | grep -q "Version:${plugin_version}"
REMOTE

echo "cnpg_plugin_install=PASS version=$plugin_version sha256=$plugin_sha256"
