#!/usr/bin/env bash
set -Eeuo pipefail

has_cmd() { command -v "$1" >/dev/null 2>&1; }

REQUIRED=(bash python3 node npm pm2 aws openssl curl systemctl)
OPTIONAL=(glow md)
SHOULD_BE_DISABLED=()
UNNECESSARY=(docker httpd apache2 nginx mysql mariadb postgresql redis mongod)

missing=()
required_ok=()
optional_found=()
disabled_ok=()
unnecessary_found=()

for x in "${REQUIRED[@]}"; do
  if has_cmd "$x"; then required_ok+=("$x"); else missing+=("$x"); fi
done

for x in "${OPTIONAL[@]}"; do
  if has_cmd "$x"; then optional_found+=("$x"); fi
done

for x in "${UNNECESSARY[@]}"; do
  if has_cmd "$x"; then unnecessary_found+=("$x"); fi
done

join_list() {
  if (($# == 0)); then
    printf 'none'
    return
  fi

  local first=1
  local item
  for item in "$@"; do
    if ((first)); then
      printf '%s' "$item"
      first=0
    else
      printf ', %s' "$item"
    fi
  done
}

if ((${#missing[@]})); then
  printf 'Missing necessary tools: %s\n' "$(join_list "${missing[@]}")"
  exit 1
fi

if ((${#unnecessary_found[@]})); then
  printf 'Unnecessary app-level tools found: %s\n' "$(join_list "${unnecessary_found[@]}")"
  exit 1
fi

printf 'Required: %s\n' "$(join_list "${required_ok[@]}")"
printf 'Optional: %s\n' "$(join_list "${optional_found[@]}")"
printf 'Disabled: %s\n' "$(join_list "${disabled_ok[@]}")"
