#!/usr/bin/env bash
# vScan Studio. The installer asks what it needs; you do not need any flags.
#
#   curl -fsSL https://get.vaktex.com/studio | sudo bash
#
# Anything after "bash -s --" is passed to the installer, for unattended use:
#   curl -fsSL https://get.vaktex.com/studio | sudo bash -s -- --help
set -Eeuo pipefail

BASE="${VSCAN_GET_URL:-https://get.vaktex.com}"

if [ "$(id -u)" -ne 0 ]; then
	echo "The installer needs root. Run: curl -fsSL $BASE/studio | sudo bash" >&2
	exit 1
fi
for tool in curl tar sha256sum; do
	command -v "$tool" >/dev/null 2>&1 || { echo "This machine is missing $tool." >&2; exit 1; }
done

DIR="${VSCAN_INSTALLER_DIR:-/opt/vscan-installer}"
rm -rf "$DIR"
mkdir -p "$DIR"

echo "Downloading the vScan Studio installer"
curl -fsSL "$BASE/studio.tar.gz" -o "$DIR/studio.tar.gz"
expected="$(curl -fsSL "$BASE/studio.tar.gz.sha256" | awk '{ print $1 }')"
actual="$(sha256sum "$DIR/studio.tar.gz" | awk '{ print $1 }')"
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
	echo "The download did not match its checksum. Nothing was installed; try again." >&2
	exit 1
fi
tar -xzf "$DIR/studio.tar.gz" -C "$DIR"
rm -f "$DIR/studio.tar.gz"

# The pipe that fed this script is bash's stdin, so the installer's questions
# are read from the terminal instead. With no terminal (automation), the
# installer runs unattended from flags and says what is missing.
export VSCAN_INSTALLER_DIR="$DIR"
if [ -e /dev/tty ] && (: </dev/tty) 2>/dev/null; then
	exec bash "$DIR/install.sh" "$@" </dev/tty
else
	exec bash "$DIR/install.sh" "$@"
fi
