#!/bin/sh
# grua's installer, the first step: fetches the installer for this
# machine, checks it's the one delta serves, and runs it on the
# terminal. It runs from a temp dir and goes when it's done: nothing
# stays on this machine. The installer asks for the license before it
# touches the cluster.
#
#   curl -sfL https://get.grua.io/install.sh | sh
set -eu

URL='https://get.grua.io'

fail() {
  printf '\033[1;31m%s\033[0m\n' "$1" >&2
  exit 1
}

# piped into sudo, sudo's own input is the pipe, not the terminal:
# sudo-rs (Ubuntu's) then keeps the keyboard, and the terminal's size,
# from the installer. It asks for sudo itself when it needs it
if [ "$(id -u)" = 0 ] && [ -n "${SUDO_USER:-}" ] && [ ! -t 0 ]; then
  fail "run it without sudo: curl -sfL $URL/install.sh | sh — it asks for sudo itself when it needs it"
fi

case "$(uname -s)" in
  Linux) os=linux ;;
  *) fail "grua's installer runs on Linux" ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) fail "grua's installer runs on amd64 and arm64" ;;
esac

case "$os-$arch" in
  linux-amd64) sum='5dda7d4acf5a2030a6774694a60b2c5377c9127f657f132009392487edb28bd6' ;;
  linux-arm64) sum='9aa3dbcd47759921c9b84be971202ea3daa2d5349d2bc8c4b4b5ffd588c22f2b' ;;
  *) fail "no installer for $os-$arch" ;;
esac

dir="$(mktemp -d)"
trap 'rm -rf "$dir"' EXIT INT TERM

curl -sSfL -o "$dir/grua-installer" "$URL/installers/$os-$arch" ||
  fail "couldn't download the installer from $URL"

if command -v sha256sum >/dev/null 2>&1; then
  got="$(sha256sum "$dir/grua-installer" | cut -d ' ' -f 1)"
else
  got="$(shasum -a 256 "$dir/grua-installer" | cut -d ' ' -f 1)"
fi
[ "$got" = "$sum" ] || fail "the installer downloaded isn't the one $URL serves"
chmod +x "$dir/grua-installer"

# on a k3s node with no kubeconfig of one's own, the installer reads
# k3s's, which is root's
run=
if [ "$(id -u)" != 0 ] && [ -z "${KUBECONFIG:-}" ] && [ ! -e "$HOME/.kube/config" ] &&
  [ -e /etc/rancher/k3s/k3s.yaml ] && [ ! -r /etc/rancher/k3s/k3s.yaml ]; then
  printf "k3s's kubeconfig is root's: the installer runs with sudo\n"
  run=sudo
fi

# the script came on stdin: the installer asks on the terminal — and so
# does sudo, its input the terminal too
if (true </dev/tty) 2>/dev/null; then
  $run "$dir/grua-installer" --url "$URL" "$@" </dev/tty
else
  $run "$dir/grua-installer" --url "$URL" "$@"
fi
