#!/bin/sh
# Download the right ygg-setup for this Mac/Linux machine, verify it, and run it.
#   curl -fsSL https://get.train-enjoyers.net/install.sh | sh
# Set YGG_SETUP_BASE to use a mirror. Extra arguments are passed to ygg-setup.
set -eu
BASE="${YGG_SETUP_BASE:-https://get.train-enjoyers.net}"

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) echo "ygg-setup: unsupported system $(uname -s); on Windows use install.ps1" >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  armv7* | armv6*) arch=arm ;;
  i386 | i686) arch=386 ;;
  *) echo "ygg-setup: unsupported CPU $(uname -m)" >&2; exit 1 ;;
esac
file="ygg-setup-$os-$arch"

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else echo "ygg-setup: need curl or wget" >&2; exit 1; fi
}

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
echo "Downloading $file from $BASE ..."
fetch "$BASE/$file" "$tmp/$file"
fetch "$BASE/SHA256SUMS" "$tmp/SHA256SUMS"

expected="$(awk -v f="$file" '$2 == f || $2 == "*" f { print $1 }' "$tmp/SHA256SUMS")"
if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$tmp/$file" | cut -d' ' -f1)"
else actual="$(shasum -a 256 "$tmp/$file" | cut -d' ' -f1)"; fi
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
  echo "ygg-setup: checksum mismatch for $file; not running it" >&2
  exit 1
fi
chmod +x "$tmp/$file"

# When piped into sh, stdin is the script itself; give ygg-setup the terminal instead
# (if there is one: /dev/tty exists but can't be opened without a controlling terminal).
in=/dev/stdin
# (Probe in a subshell: a failed redirect on a special built-in exits a POSIX shell.)
if [ ! -t 0 ] && (: </dev/tty) 2>/dev/null; then in=/dev/tty; fi
if [ "$(id -u)" -eq 0 ]; then
  "$tmp/$file" "$@" <"$in"
else
  sudo -- "$tmp/$file" "$@" <"$in"
fi
