#!/bin/sh
# Girder one-command installer.
#
#   curl -fsSL https://dl.rungirder.com/platform/install.sh | sh -s -- \
#     --domain apps.example.com --email you@example.com \
#     --cf-token <token> --cf-zone <zone> --tailscale-key <tskey-...> \
#     [--hcloud-token <token>] [--license <path-or-url>]
#
# Run with no arguments to be prompted interactively instead.
# What it does: downloads the latest Girder binary for this architecture,
# verifies it against the published SHA256SUMS, installs it to
# /opt/girder/girder, then runs `girder init` with your arguments
# (docker, tailscale, firewall, daemon, config, wildcard DNS).
set -eu

BASE="https://dl.rungirder.com/platform"
DEST="/opt/girder/girder"

if [ "$(id -u)" != "0" ]; then
  echo "run as root (sudo sh)" >&2
  exit 1
fi

arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) target="linux-amd64" ;;
  aarch64|arm64) target="linux-arm64" ;;
  *) echo "unsupported architecture: $arch" >&2; exit 1 ;;
esac

echo "==> fetching latest version"
latest="$(curl -fsSL "$BASE/LATEST")"
echo "==> downloading Girder $latest ($target)"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL -o "$tmp/girder" "$BASE/$latest/girder-$latest-$target"
curl -fsSL -o "$tmp/SHA256SUMS" "$BASE/$latest/SHA256SUMS"

echo "==> verifying checksum"
want="$(grep "girder-$latest-$target\$" "$tmp/SHA256SUMS" | awk '{print $1}')"
if [ -z "$want" ]; then
  echo "no checksum for girder-$latest-$target in SHA256SUMS" >&2
  exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
  got="$(sha256sum "$tmp/girder" | awk '{print $1}')"
else
  got="$(shasum -a 256 "$tmp/girder" | awk '{print $1}')"
fi
if [ "$got" != "$want" ]; then
  echo "checksum mismatch — aborting (got $got, want $want)" >&2
  exit 1
fi

mkdir -p /opt/girder
mv "$tmp/girder" "$DEST"
chmod 755 "$DEST"

echo "==> installed $DEST ($latest)"
if [ "$#" -gt 0 ]; then
  exec "$DEST" init "$@"
else
  # Interactive: prompt for the init answers on the real terminal.
  exec "$DEST" init < /dev/tty
fi
