#!/usr/bin/env bash
#===============================================================================
#
#             FILE: helm.sh
#            USAGE: curl -fsSL https://install.gutocarvalho.net/helm.sh | bash
#
#      DESCRIPTION: installs helm 3 using the official get-helm-3 script, into
#                   /usr/local/bin.
#
#     REQUIREMENTS: curl, 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: 2026-08-15
#          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. HELPERS #################################################################

### abort: print an error message and stop the script
function abort() {
  echo -e "\nError: $1" >&2
  echo -e "Tip: run 'bash -x helm.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
}

## 2. INSTALL FUNCTIONS #######################################################

### install helm
function install_helm() {
  echo -e "\n>>> Installing helm...\n"
  curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
  command -v helm >/dev/null 2>&1 || abort "helm installation failed."
  echo "helm $(helm version --short 2>/dev/null) installed."
}

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

check_root
need_cmd curl

refuse_if_present helm

install_helm

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

echo -e "\nAll done! helm is available at /usr/local/bin/helm."
