#!/usr/bin/env bash
# EasyOps server - one-line installer (downloads the bundle, verifies it, runs install.sh)
#
#   curl -fsSL https://install-easyops.rocketai.info/get.sh | sudo bash -s -- --domain easyops.example.com --admin mike
#
# All arguments are passed to install.sh (see: ... | sudo bash -s -- --help).
# Own admin password:  ... | sudo EASYOPS_ADMIN_PASSWORD='secret123' bash -s -- --domain ...
# Everything runs inside main() so a partially downloaded script never executes.
main() {
  set -euo pipefail
  local base="${EASYOPS_BUNDLE_BASE:-https://install-easyops.rocketai.info}"
  local zip="easyops-server-20261116.zip"
  local sha="389573c75126767af697a0a8b5cef444498dc2c1a2641b23535bb56400d01f2a"
  die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
  say() { printf '\033[1;32m==>\033[0m %s\n' "$*"; }

  case " $* " in *" -h "*|*" --help "*) ;; *) [ "$(id -u)" -eq 0 ] || die "must run as root: curl -fsSL $base/get.sh | sudo bash -s -- --domain ..." ;; esac
  command -v curl >/dev/null 2>&1 || die "curl is required"
  command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required"

  local tmp; tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' EXIT
  say "Downloading $base/$zip"
  curl -fsSL "$base/$zip" -o "$tmp/$zip"
  echo "$sha  $tmp/$zip" | sha256sum -c --quiet - || die "checksum mismatch - download corrupted or tampered with"
  say "Checksum OK"

  if command -v unzip >/dev/null 2>&1; then unzip -q "$tmp/$zip" -d "$tmp"
  elif command -v python3 >/dev/null 2>&1; then python3 -m zipfile -e "$tmp/$zip" "$tmp"
  elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y unzip >/dev/null || { apt-get update >/dev/null && DEBIAN_FRONTEND=noninteractive apt-get install -y unzip >/dev/null; }; unzip -q "$tmp/$zip" -d "$tmp"
  elif command -v dnf >/dev/null 2>&1; then dnf install -y unzip >/dev/null; unzip -q "$tmp/$zip" -d "$tmp"
  else die "need unzip or python3 to unpack the bundle"; fi
  [ -f "$tmp/easyops/install.sh" ] || die "bundle incomplete"
  (cd "$tmp/easyops" && sha256sum -c --quiet SHA256SUMS) || die "file checksums inside the bundle do not match"

  bash "$tmp/easyops/install.sh" "$@"
}
main "$@"
