#!/bin/sh
# RootBase one-line installer.
#   cd /home && curl -o latest -L https://rootmanage.com/rootbase/latest && sh latest [panel.yourdomain.com]
# It downloads RootBase, checks the download against its published SHA-256, and runs the installer inside it.
# Read this file first if you like: it only downloads, checks and unpacks. The real work is in tools/install.sh inside the download.
[ -n "$BASH_VERSION" ] || { command -v bash >/dev/null 2>&1 && exec bash "$0" "$@"; echo "bash is required (install it first, for example: yum -y install bash)"; exit 1; }
set -euo pipefail

BASE="${ROOTBASE_URL:-https://rootmanage.com/downloads}"
FILE="${ROOTBASE_FILE:-rootbase-latest.tar.gz}"
[ "$(id -u)" = 0 ] || { echo "Run this as root (log in as root, or use: sudo sh latest)."; exit 1; }
command -v curl >/dev/null || { echo "curl is required. Install it first:  yum -y install curl   (AlmaLinux, Rocky, CentOS)   or   apt-get install -y curl   (Ubuntu, Debian)"; exit 1; }
command -v tar >/dev/null || { echo "tar is required. Install it first:  yum -y install tar   or   apt-get install -y tar"; exit 1; }

TMP="$(mktemp -d /tmp/rootbase-install.XXXXXX)"
trap 'rm -rf "$TMP"' EXIT
if [ -t 1 ]; then printf '\n\033[1;36m  ROOTMANAGE\033[0m  RootBase installer\n\n'; else printf '\n  ROOTMANAGE  RootBase installer\n\n'; fi
echo "==> Downloading RootBase"
curl -fsSL --retry 3 -o "$TMP/$FILE" "$BASE/$FILE"
curl -fsSL --retry 3 -o "$TMP/$FILE.sha256" "$BASE/$FILE.sha256"

echo "==> Checking the download"
WANT="$(awk '{print $1}' "$TMP/$FILE.sha256")"
if command -v sha256sum >/dev/null; then GOT="$(sha256sum "$TMP/$FILE" | awk '{print $1}')"; else GOT="$(shasum -a 256 "$TMP/$FILE" | awk '{print $1}')"; fi
[ -n "$WANT" ] && [ "$WANT" = "$GOT" ] || { echo "The download does not match its checksum. Nothing was installed. Try again in a minute."; exit 1; }

mkdir -p "$TMP/src"
tar -xzf "$TMP/$FILE" -C "$TMP/src" --strip-components=1
[ -f "$TMP/src/server.js" ] && [ -f "$TMP/src/tools/install.sh" ] || { echo "The download is not a RootBase package. Nothing was installed."; exit 1; }
if [ "${ROOTBASE_DRY_RUN:-}" = 1 ]; then echo "Dry run: the download is good and was unpacked. Stopping before the install."; ls "$TMP/src" | head -5; exit 0; fi
bash "$TMP/src/tools/install.sh" "$@"
