#!/usr/bin/env bash
#===============================================================================
#
#             FILE: k8s-tools.sh
#            USAGE: curl -fsSL https://install.gutocarvalho.net/k8s-tools.sh | bash
#
#      DESCRIPTION: installs kubectl, kubetail, helm, velero and k9s on
#                   compatible linux hosts (amd64).
#
#                   This is an aggregator: it just downloads and runs the
#                   focused, single-tool scripts (kubectl.sh, kubetail.sh,
#                   helm.sh, velero.sh, k9s.sh) in order. Each of those can
#                   still be run on its own (e.g. curl .../velero.sh | bash).
#
#     REQUIREMENTS: curl, wget, tar, bash
#
#       OS SUPPORT: Linux
#   DISTRO SUPPORT: Debian-like
#             ARCH: amd64
#
#           AUTHOR: Guto Carvalho, guto@bolha.io
#             SITE: https://gutocarvalho.net
#         MASTODON: @gutocarvalho@bolha.us
#         PIXELFED: @gutocarvalho@bolha.photos
#      WRITEFREELY: @gutocarvalho@bolha.blog
#       MATTERMOST: @gutocarvalho:mattermost.bolha.chat
#
#     ORGANIZATION: gutocarvalho.net, gcn.sh, bolha.io
#
#          CREATED: 2025-01-29
#          UPDATED: 2026-08-15
#             REPO: https://gitlab.gutocarvalho.net/open/install
#
#     CONTRIBUTORS: name, email, mastodon
#
#     The code is simple on purpose: we want it to be friendly for people
#     that are starting with shell language and programming logic.
#
#     This script was designed to run on a clean, brand new machine/vm/vps.
#
#===============================================================================

set -o nounset                              # treat unset variables as an error

## 1. CONSTANTS/VARIABLES ######################################################

# where to download the focused scripts from (override with INSTALL_BASE_URL)
BASE_URL="${INSTALL_BASE_URL:-https://install.gutocarvalho.net}"

# focused scripts to run, in order -> script:binary (binary is used to fail fast
# if the tool is already installed, before we download anything)
TARGETS="
kubectl.sh:kubectl
kubetail.sh:kubetail
helm.sh:helm
velero.sh:velero
k9s.sh:k9s
"

## 2. HELPERS #################################################################

### abort: print an error message and stop the script
function abort() {
  echo -e "\nError: $1" >&2
  echo -e "Tip: run 'bash -x k8s-tools.sh' to see exactly what failed.\n" >&2
  exit 1
}

### check_root: this script must run as root
function check_root() {
  if [ "$(id -u)" != "0" ]; then
    abort "this script needs to run as root. Become root with 'su -' or 'sudo -i', then try again."
  fi
}

### need_cmd: make sure a required command exists
function need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    abort "'$1' is required but was not found. Please install it first."
  fi
}

### refuse_if_present: stop if the tool we are about to install already exists
function refuse_if_present() {
  if command -v "$1" >/dev/null 2>&1; then
    abort "'$1' is already installed at $(command -v "$1"). Remove it first, then run this script again."
  fi
}

### run_one: download and run a focused script (fail closed on any problem)
function run_one() {
  local script="$1" tmp
  echo -e "\n==> Running $script from $BASE_URL ...\n"
  tmp=$(mktemp)
  curl -fsSL "$BASE_URL/$script" -o "$tmp" || { rm -f "$tmp"; abort "could not download $BASE_URL/$script."; }

  # fail closed: never run an empty file or something that is not a shell script
  if [ ! -s "$tmp" ] || ! head -n1 "$tmp" | grep -q '^#!'; then
    rm -f "$tmp"
    abort "the downloaded '$script' does not look like a script, refusing to run it."
  fi

  bash "$tmp"
  local rc=$?
  rm -f "$tmp"
  [ "$rc" -eq 0 ] || abort "'$script' failed (exit $rc). Stopping here."
}

## 3. EXECUTING ###############################################################

check_root
need_cmd curl
need_cmd wget
need_cmd tar

# fail fast: if any of the tools is already installed, stop before downloading
for entry in $TARGETS; do
  refuse_if_present "${entry#*:}"
done

# install each tool by running its focused script
for entry in $TARGETS; do
  run_one "${entry%%:*}"
done

## 4. NOTIFICATIONS ###########################################################

echo -e "\n----------------------------------------------------------------------------------"
echo -e "\nAll done! kubectl, kubetail, helm, velero and k9s are installed in /usr/local/bin."
echo -e "\nEnjoy it!"
echo -e "\nWant to know more about our collective? Visit https://bolha.io and consider joining us! ;)"
echo -e "Come and visit our mastodon instance:    https://bolha.us"
echo -e "Come and visit our mattermost instance:  https://mattermost.bolha.chat"
echo -e "Say hello on the fediverse:              @gutocarvalho@bolha.us"
echo -e "\n----------------------------------------------------------------------------------\n"
