#!/usr/bin/env bash
# Minaki Tuner client installer.   Download it, check it against the published sha256, then: sudo bash install.sh <LICENSE KEY>
# Installs the client and prints a first report. It reads your server; it changes nothing but its own files.
set -euo pipefail
main() {
  BASE='https://minakilabs.com/minaki'
  SUM='93add58096bc8860b60c60de59ac07809ef26a00454d463de1fa5f8b9989a59b'
  R=${MINAKI_ROOT:-}
  die() { echo "minaki-tuner: $*" >&2; exit 1; }
  key=${1:-}
  [ -n "$key" ] || die "your license key is missing.  Use:  sudo bash install.sh <LICENSE KEY>"
  [ "$(id -u)" = 0 ] || [ -n "${MINAKI_NOT_ROOT_OK:-}" ] || die "run it with sudo"
  read -r kernel arch <<< "${MINAKI_UNAME:-$(uname -r) $(uname -m)}"
  if ! { ( ID= VERSION_ID=; . "$R/etc/os-release" 2>/dev/null; [ "$ID $VERSION_ID" = "ubuntu 22.04" ] ) && [ "$arch" = x86_64 ]; }; then
    [ "${TUNER_UNSUPPORTED:-}" = 1 ] && echo "UNSUPPORTED PLATFORM (lab override, not a supported run)" >&2 ||
      die "Minaki Tuner currently supports Ubuntu 22.04 LTS. Ubuntu 24.04 and Rocky Linux support is coming soon. This server is $( ID= VERSION_ID=; . "$R/etc/os-release" 2>/dev/null; echo "${ID:-unknown} ${VERSION_ID:-}") on $arch. Nothing was installed."
  fi
  for c in curl openssl python3 tar sha256sum; do command -v $c >/dev/null || die "the program '$c' is missing; nothing was installed"; done
  tmp=$(mktemp -d); trap 'rm -rf -- "${tmp:?}"' EXIT
  curl -fsSL -o "$tmp/c.tar.gz" "$BASE/minaki-tuner-client.tar.gz" || die "the download failed; nothing was installed"
  echo "$SUM  $tmp/c.tar.gz" | sha256sum -c --quiet - >/dev/null 2>&1 || die "the download is not the file this installer expects; nothing was installed"
  mkdir "$tmp/c"; tar xzf "$tmp/c.tar.gz" -C "$tmp/c" --no-same-owner
  python3 -I -B "$tmp/c/minaki-tuner" verify-license "$key" || die "nothing was installed"
  umask 022
  mkdir -p "$R/opt" "$R/usr/local/bin" "$R/etc/minaki-tuner"
  rm -rf -- "${R}/opt/minaki-tuner"; cp -r "$tmp/c" "$R/opt/minaki-tuner"; chmod 755 "$R/opt/minaki-tuner" "$R/opt/minaki-tuner/minaki-tuner"
  ln -sfn /opt/minaki-tuner/minaki-tuner "$R/usr/local/bin/minaki-tuner"
  ( umask 077; printf '%s\n' "$key" > "$R/etc/minaki-tuner/license" ); chmod 600 "$R/etc/minaki-tuner/license"
  echo "Minaki Tuner client installed. Reading your server (nothing is changed)..."
  [ -n "${MINAKI_NO_REPORT:-}" ] || /opt/minaki-tuner/minaki-tuner report
}
main "$@"
