#!/bin/sh
# all-aboard: kubectl for Heap, the Recurse Center's community cluster.
#
#   curl -fsSL https://<this site>/install.sh | sh
#   curl -fsSL https://<this site>/install.sh | sh -s -- --device
#
# Read it before you run it:  curl -fsSL https://<this site>/install.sh | less
#
# What it does, in order:
#   1. Finds kubectl and kubelogin, and installs whichever is missing:
#      Homebrew on a Mac that has it, otherwise a pinned binary checked
#      against the SHA-256 below, into ~/.local/bin.
#   2. Writes ~/.kube/heap.yaml, backing up any older copy that differs.
#   3. Checks that Heap's API answers, then runs `kubectl auth whoami`,
#      which logs you in with your RC account through batchmate.id.
#
# It never uses sudo, never edits your shell's rc files, and never touches
# ~/.kube/config. Nothing in the kubeconfig is secret.
#
# The whole script is inside main(), called on the last line, so a download
# cut off halfway runs nothing.

set -eu

# --- Heap -------------------------------------------------------------------

HEAP_SERVER_DEFAULT="https://k8s.cluster.recurse.com:6443"
# Heap's server CA, base64: k3s's server CA on crosby, the cluster's one server
# (/var/lib/rancher/k3s/server/tls/server-ca.crt, also served at /cacerts).
# CN=k3s-server-ca@1795552714, valid until 2036-11-21, SHA-256
# 39:91:CF:5A:91:42:2A:F1:85:7C:B0:6F:D7:2C:56:74:B6:1B:DD:1B:81:39:2D:E4:12:49:7A:F9:BD:0E:20:DB
# A rebuilt crosby has a new one; until it's pasted here, every run stops at
# "a certificate Heap's CA didn't sign".
HEAP_CA_DATA_DEFAULT="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJlRENDQVIyZ0F3SUJBZ0lCQURBS0JnZ3Foa2pPUFFRREFqQWpNU0V3SHdZRFZRUUREQmhyTTNNdGMyVnkKZG1WeUxXTmhRREUzT1RVMU5USTNNVFF3SGhjTk1qWXhNVEkwTVRrek9ETTBXaGNOTXpZeE1USXhNVGt6T0RNMApXakFqTVNFd0h3WURWUVFEREJock0zTXRjMlZ5ZG1WeUxXTmhRREUzT1RVMU5USTNNVFF3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFTVUhFWlpXTU8wbGFFWTBxd0tXM3B5cVZwMk8wcU42dSt5eFREMGhBWVQKY0VvL2NNSWM1NE04ZStpcnVXYitPbGc0a1RNMitLWDRHemlidkQwRDNXeDJvMEl3UURBT0JnTlZIUThCQWY4RQpCQU1DQXFRd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZEJnTlZIUTRFRmdRVTZFY015ZnlYWXlyVEY1MzJpYXduCk10Tk9GeGN3Q2dZSUtvWkl6ajBFQXdJRFNRQXdSZ0loQU84OGc2aU9zZ002ckY1WjVNL2VEYVVQUWxKUk82RFUKM3labjNPU1UybTdzQWlFQTluRWowOWFXNjJhRDhpaEZhOGMyWEY4SlV5c2UyZzBzaWxwZTdJUnlaekE9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"
OIDC_ISSUER="https://batchmate.id"
# batchmate.id's public client for kubectl. A public client has no secret.
OIDC_CLIENT_ID="pub_9ed1dcf899a8769ecf87214029ee2bcc"

# --- Pinned tools -----------------------------------------------------------
# kubectl matches k3s_version in cluster-config's roles/k3s/defaults/main.yml.
# To bump either, see "Bumping a tool" in the repo's README.

KUBECTL_VERSION="v1.36.6"
KUBELOGIN_VERSION="v1.36.4"

kubectl_sha256() {
	case "$1" in
	linux_amd64) echo 29818b6729dc9262b692307470d0558d027725e738be5dd47c760261868a2634 ;;
	linux_arm64) echo 35507ef408c3d38849e5d3203e18f8e861db822aa664101a9ced0869edd06046 ;;
	darwin_amd64) echo 2e22d382f2423c88d9d076246f860bb3d5c743dd279ca63e113474bb88382426 ;;
	darwin_arm64) echo 1cf735c3d35ccfec28d0618784cb06a4614d2c42aade28b6be0eab76a2ffb623 ;;
	*) return 1 ;;
	esac
}

# These are the sums of the release zips, not of the binary inside.
kubelogin_sha256() {
	case "$1" in
	linux_amd64) echo 9e8baeb4905d35a301304af2548324997add512fe94ab20e65993d167212bf85 ;;
	linux_arm64) echo 669c2d3bcc6766351ad5a7b03971792b4e7a55117b335a12d9858d43a525d9dc ;;
	darwin_amd64) echo 7927b10c122b55dd4d9632f75d56752bfdc5f7b6ad3104615115c02f5f55e4f0 ;;
	darwin_arm64) echo 5aa470d059a9672d732439474678ac05a0de5623ad3af54966b8fe1ac7df4254 ;;
	*) return 1 ;;
	esac
}

# --- Helpers ----------------------------------------------------------------

say() { printf 'all-aboard: %s\n' "$*" >&2; }
die() {
	printf 'all-aboard: %s\n' "$*" >&2
	exit 1
}
have() { command -v "$1" >/dev/null 2>&1; }

usage() {
	cat <<'EOF'
Usage: install.sh [options]

  --device          log in with a code you approve on another device
                    (the default over SSH, or on Linux with no display)
  --browser         log in through a browser on this machine
  --no-install      don't install kubectl or kubelogin; say how instead
  --no-login        write the kubeconfig and stop
  --kubeconfig PATH write here instead of ~/.kube/heap.yaml
  --print           print a generic kubeconfig to stdout and change nothing
  -h, --help        this

Environment, for rehearsing against something that isn't Heap:
  HEAP_SERVER       API URL (default https://k8s.cluster.recurse.com:6443)
  HEAP_CA_DATA      the server's CA, base64
EOF
}

# platform prints linux_amd64, darwin_arm64 and so on, or fails.
platform() {
	case "$(uname -s)" in
	Linux) os=linux ;;
	Darwin) os=darwin ;;
	*) return 1 ;;
	esac
	case "$(uname -m)" in
	x86_64 | amd64) arch=amd64 ;;
	aarch64 | arm64) arch=arm64 ;;
	*) return 1 ;;
	esac
	echo "${os}_${arch}"
}

fetch() { # url dest
	if have curl; then
		curl -fsSL --retry 2 -o "$2" "$1" || die "failed to download $1"
	elif have wget; then
		wget -q -O "$2" "$1" || die "failed to download $1"
	else
		die "need curl or wget to download $1"
	fi
}

sha256_of() {
	if have sha256sum; then
		sha256sum "$1" | cut -d' ' -f1
	elif have shasum; then
		shasum -a 256 "$1" | cut -d' ' -f1
	else
		die "need sha256sum or shasum to check downloads"
	fi
}

verify() { # file want
	got=$(sha256_of "$1")
	[ "$got" = "$2" ] || die "checksum mismatch on $(basename "$1"): want $2, got $got. Nothing was installed."
}

use_brew() {
	[ "$(uname -s)" = Darwin ] && [ -z "${ALL_ABOARD_NO_BREW:-}" ] && have brew
}

on_path() { # dir
	case ":$PATH:" in *":$1:"*) return 0 ;; *) return 1 ;; esac
}

# install_file stages into the destination directory so replacement stays atomic
# even when $TMP and $HOME are on different filesystems (e.g. tmpfs and NFS).
install_file() { # src dest mode
	dest_dir=$(dirname "$2")
	mkdir -p "$dest_dir"
	STAGED="$dest_dir/.$(basename "$2").tmp.$$"
	cp "$1" "$STAGED"
	chmod "$3" "$STAGED"
	mv "$STAGED" "$2"
	STAGED=""
}

# is_oidc_kubelogin rejects Azure's kubelogin, which shares the binary name
# but doesn't accept --oidc-issuer-url.
is_oidc_kubelogin() { # bin
	out=$("$1" get-token --help 2>&1) || return 1
	case "$out" in
	*--oidc-issuer-url*) return 0 ;;
	*) return 1 ;;
	esac
}

# yaml_scalar quotes a path for YAML when it has anything but plain characters.
yaml_scalar() {
	case "$1" in
	"" | *[!A-Za-z0-9/._-]*) printf "'%s'" "$(printf '%s' "$1" | sed "s/'/''/g")" ;;
	*) printf '%s' "$1" ;;
	esac
}

# --- Tools ------------------------------------------------------------------

MISSING=""

missing() { # name how
	MISSING="$MISSING
  $1: $2"
}

kubectl_hint() {
	if [ "$(uname -s)" = Darwin ]; then
		echo "brew install kubectl"
	else
		echo "https://kubernetes.io/docs/tasks/tools/#kubectl"
	fi
}

kubelogin_hint() {
	if [ "$(uname -s)" = Darwin ]; then
		echo "brew install kubelogin"
	else
		echo "kubectl krew install oidc-login, or a binary from https://github.com/int128/kubelogin/releases"
	fi
}

# ensure_kubectl sets KUBECTL to a kubectl that runs.
ensure_kubectl() {
	if have kubectl; then
		KUBECTL=$(command -v kubectl)
		say "kubectl: $KUBECTL"
		return
	fi
	if [ -x "$BIN/kubectl" ]; then
		KUBECTL="$BIN/kubectl"
		say "kubectl: $KUBECTL"
		return
	fi
	if [ "$INSTALL" = 0 ]; then
		missing kubectl "$(kubectl_hint)"
		return
	fi
	if use_brew; then
		say "installing kubectl with Homebrew"
		brew install kubectl </dev/null
		KUBECTL=$(command -v kubectl) || die "Homebrew installed kubectl, but it isn't on PATH"
		return
	fi
	plat=$(platform) || die "no kubectl for $(uname -s) $(uname -m) here. Install it yourself: $(kubectl_hint)"
	sum=$(kubectl_sha256 "$plat")
	say "downloading kubectl $KUBECTL_VERSION for $plat"
	fetch "https://dl.k8s.io/release/$KUBECTL_VERSION/bin/${plat%_*}/${plat#*_}/kubectl" "$TMP/kubectl"
	verify "$TMP/kubectl" "$sum"
	install_file "$TMP/kubectl" "$BIN/kubectl" 0755
	KUBECTL="$BIN/kubectl"
	say "kubectl: $KUBECTL"
}

# ensure_kubelogin sets LOGIN_CMD to the absolute path of int128/kubelogin
# (including krew's kubectl-oidc_login binary), so tools started without your
# shell's PATH still work.
ensure_kubelogin() {
	foreign_kubelogin=0
	if have kubelogin; then
		cand=$(command -v kubelogin)
		if is_oidc_kubelogin "$cand"; then
			LOGIN_CMD=$cand
			say "kubelogin: $LOGIN_CMD"
			return
		fi
		say "$cand isn't int128/kubelogin (Azure kubelogin?); ignoring it"
		foreign_kubelogin=1
	fi
	if [ -x "$BIN/kubelogin" ]; then
		if is_oidc_kubelogin "$BIN/kubelogin"; then
			LOGIN_CMD="$BIN/kubelogin"
			say "kubelogin: $LOGIN_CMD"
			return
		fi
		die "$BIN/kubelogin exists, but isn't int128/kubelogin. Move it aside or install kubectl-oidc_login."
	fi
	if have kubectl-oidc_login; then
		cand=$(command -v kubectl-oidc_login)
		if is_oidc_kubelogin "$cand"; then
			LOGIN_CMD=$cand
			say "kubelogin: $LOGIN_CMD"
			return
		fi
	fi
	krew_bin="${KREW_ROOT:-$HOME/.krew}/bin/kubectl-oidc_login"
	if [ -x "$krew_bin" ] && is_oidc_kubelogin "$krew_bin"; then
		LOGIN_CMD=$krew_bin
		say "kubelogin: $LOGIN_CMD"
		return
	fi
	if [ "$INSTALL" = 0 ]; then
		missing kubelogin "$(kubelogin_hint)"
		return
	fi
	if use_brew && [ "$foreign_kubelogin" = 0 ]; then
		say "installing kubelogin with Homebrew"
		brew install kubelogin </dev/null
		LOGIN_CMD=$(command -v kubelogin) || die "Homebrew installed kubelogin, but it isn't on PATH"
		return
	fi
	plat=$(platform) || die "no kubelogin for $(uname -s) $(uname -m) here. Install it yourself: $(kubelogin_hint)"
	sum=$(kubelogin_sha256 "$plat")
	zip="kubelogin_$plat.zip"
	say "downloading kubelogin $KUBELOGIN_VERSION for $plat"
	fetch "https://github.com/int128/kubelogin/releases/download/$KUBELOGIN_VERSION/$zip" "$TMP/$zip"
	verify "$TMP/$zip" "$sum"
	if have unzip; then
		unzip -q -o "$TMP/$zip" kubelogin -d "$TMP"
	elif have python3; then
		python3 -I -c 'import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extract("kubelogin", sys.argv[2])' "$TMP/$zip" "$TMP"
	else
		die "need unzip or python3 to unpack kubelogin"
	fi
	install_file "$TMP/kubelogin" "$BIN/kubelogin" 0755
	LOGIN_CMD="$BIN/kubelogin"
	say "kubelogin: $LOGIN_CMD"
}

# --- The kubeconfig ---------------------------------------------------------

# kubeconfig prints the kubeconfig for LOGIN_CMD, FLOW, SERVER, CA.
kubeconfig() {
	cat <<EOF
# Heap's kubeconfig, from all-aboard. Nothing in it is secret.
apiVersion: v1
kind: Config
clusters:
  - name: heap
    cluster:
      server: $SERVER
      certificate-authority-data: $CA
users:
  - name: recurse
    user:
      exec:
        apiVersion: client.authentication.k8s.io/v1
        command: $(yaml_scalar "$LOGIN_CMD")
        args:
          - get-token
          - --oidc-issuer-url=$OIDC_ISSUER
          - --oidc-client-id=$OIDC_CLIENT_ID
          # profile carries your RC id. Without it you're batchmate:sub_...
          - --oidc-extra-scope=profile
          - --oidc-extra-scope=email
EOF
	if [ "$FLOW" = device ]; then
		cat <<'EOF'
          - --grant-type=device-code
          - --skip-open-browser
EOF
	fi
	cat <<'EOF'
        interactiveMode: IfAvailable
contexts:
  - name: heap
    context:
      cluster: heap
      user: recurse
current-context: heap
EOF
}

detect_flow() {
	if [ -n "${SSH_CONNECTION:-}${SSH_TTY:-}${SSH_CLIENT:-}" ]; then
		echo device
		return
	fi
	case "$(uname -s)" in
	Darwin) echo browser ;;
	*)
		if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
			echo browser
		else
			echo device
		fi
		;;
	esac
}

write_kubeconfig() {
	kubeconfig >"$TMP/heap.yaml"
	if [ -f "$KUBECONFIG_PATH" ] && cmp -s "$TMP/heap.yaml" "$KUBECONFIG_PATH"; then
		chmod 0600 "$KUBECONFIG_PATH"
		say "$KUBECONFIG_PATH is already up to date"
		return
	fi
	mkdir -p "$(dirname "$KUBECONFIG_PATH")"
	if [ -f "$KUBECONFIG_PATH" ]; then
		backup="$KUBECONFIG_PATH.$(date +%Y%m%d%H%M%S).bak"
		cp -p "$KUBECONFIG_PATH" "$backup"
		say "backed up the old one to $backup"
	fi
	install_file "$TMP/heap.yaml" "$KUBECONFIG_PATH" 0600
	say "wrote $KUBECONFIG_PATH ($FLOW login)"
}

# check_api fails with a reason when Heap's API doesn't answer, or answers
# with a certificate Heap's CA didn't sign. Skipped without curl.
check_api() {
	have curl || return 0
	printf '%s' "$CA" >"$TMP/ca.b64"
	base64 -d <"$TMP/ca.b64" >"$TMP/ca.crt" 2>/dev/null ||
		base64 -D <"$TMP/ca.b64" >"$TMP/ca.crt" 2>/dev/null ||
		die "the CA isn't valid base64"
	rc=0
	curl -s -o /dev/null --max-time 8 --cacert "$TMP/ca.crt" "$SERVER/version" || rc=$?
	host=${SERVER#*://}
	host=${host%%/*}
	case "$host" in
	\[*\]*) host=${host%%]*}] ;;
	*) host=${host%%:*} ;;
	esac
	case $rc in
	0) return 0 ;;
	6) die "can't resolve $host. Check your DNS; a VPN's resolver may not see it." ;;
	7 | 28) die "$SERVER didn't answer. Heap's API only answers on RC's network, and there's no tunnel. A VPN that carries all your traffic takes you off RC's network even at the hub; turn it off. $KUBECONFIG_PATH is ready: run KUBECONFIG=$KUBECONFIG_PATH kubectl auth whoami once you're on RC's network." ;;
	77) die "the CA decodes, but isn't a certificate curl can read" ;;
	35 | 51 | 58 | 60 | 83 | 90 | 91) die "$SERVER answered with a certificate Heap's CA didn't sign (curl exit $rc). Ask in #heap community cluster on Zulip." ;;
	*) die "couldn't reach $SERVER (curl exit $rc)" ;;
	esac
}

# run_whoami reattaches /dev/tty when the script is piped (`curl ... | sh`),
# so kubectl sees a terminal and passes interactive=true to kubelogin.
run_whoami() {
	if [ ! -t 0 ] && (exec </dev/tty) 2>/dev/null; then
		KUBECONFIG="$KUBECONFIG_PATH" "$KUBECTL" auth whoami </dev/tty
	else
		KUBECONFIG="$KUBECONFIG_PATH" "$KUBECTL" auth whoami
	fi
}

print_path_hint() {
	if [ "${KUBECTL:-}" = "$BIN/kubectl" ] && ! on_path "$BIN"; then
		say "$BIN isn't on your PATH. Add it in your shell's rc file:  export PATH=\"$BIN:\$PATH\""
	fi
}

cleanup() {
	[ -n "${STAGED:-}" ] && rm -f "$STAGED"
	[ -n "${TMP:-}" ] && rm -rf "$TMP"
}

# --- Main -------------------------------------------------------------------

main() {
	FLOW=""
	INSTALL=1
	LOGIN=1
	PRINT=0
	KUBECONFIG_PATH="$HOME/.kube/heap.yaml"
	BIN="$HOME/.local/bin"
	TMP=""
	STAGED=""

	while [ $# -gt 0 ]; do
		case "$1" in
		--device) FLOW=device ;;
		--browser) FLOW=browser ;;
		--no-install) INSTALL=0 ;;
		--no-login) LOGIN=0 ;;
		--print) PRINT=1 ;;
		--kubeconfig)
			[ $# -ge 2 ] && [ -n "$2" ] || die "--kubeconfig needs a path"
			KUBECONFIG_PATH=$2
			shift
			;;
		--kubeconfig=*)
			KUBECONFIG_PATH=${1#--kubeconfig=}
			[ -n "$KUBECONFIG_PATH" ] || die "--kubeconfig needs a path"
			;;
		-h | --help)
			usage
			exit 0
			;;
		*) die "unknown option $1 (try --help)" ;;
		esac
		shift
	done

	SERVER=${HEAP_SERVER:-$HEAP_SERVER_DEFAULT}
	SERVER=${SERVER%/}
	CA=$(printf '%s' "${HEAP_CA_DATA:-$HEAP_CA_DATA_DEFAULT}" | tr -d ' \t\r\n')

	# --print is the generic file served as heap.yaml: Homebrew's kubelogin on
	# PATH, browser login unless --device.
	if [ "$PRINT" = 1 ]; then
		LOGIN_CMD=kubelogin
		FLOW=${FLOW:-browser}
		CA=${CA:-TODO-heap-ca-not-published-yet}
		kubeconfig
		exit 0
	fi

	[ -n "$CA" ] || die "no CA to check Heap's certificate against: HEAP_CA_DATA_DEFAULT is empty and HEAP_CA_DATA isn't set."
	FLOW=${FLOW:-$(detect_flow)}

	TMP=$(mktemp -d)
	trap cleanup EXIT
	trap 'cleanup; exit 130' INT
	trap 'cleanup; exit 143' TERM

	ensure_kubectl
	ensure_kubelogin
	if [ -n "$MISSING" ]; then
		die "missing tools. Install them and run this again:$MISSING"
	fi
	write_kubeconfig

	if [ "$LOGIN" = 0 ]; then
		print_path_hint
		say "skipping the login. To log in:  KUBECONFIG=$KUBECONFIG_PATH kubectl auth whoami"
		exit 0
	fi

	check_api
	if [ "$FLOW" = device ]; then
		say "logging in: open the link below on any device and approve the code within 10 minutes"
	else
		say "logging in: a browser opens on batchmate.id, which sends you to recurse.com and back"
	fi
	if ! run_whoami; then
		die "the login failed. The troubleshooting table on this site's front page covers the usual causes."
	fi

	if [ -f "$HOME/.kube/config" ] && [ "$KUBECONFIG_PATH" != "$HOME/.kube/config" ]; then
		cat >&2 <<EOF

all-aboard: you're on Heap. Use it with
  export KUBECONFIG=$KUBECONFIG_PATH
or keep your existing ~/.kube/config contexts alongside it:
  export KUBECONFIG="\$HOME/.kube/config:$KUBECONFIG_PATH"
Put the line you want in your shell's rc file. A login lasts 8 hours; to log
out, delete ~/.kube/cache/oidc-login.
EOF
	else
		cat >&2 <<EOF

all-aboard: you're on Heap. Use it with
  export KUBECONFIG=$KUBECONFIG_PATH
or put that line in your shell's rc file. A login lasts 8 hours; to log out,
delete ~/.kube/cache/oidc-login.
EOF
	fi
	print_path_hint
}

main "$@"
