#!/bin/sh
# Bosun host installer: https://bosunmux.app
#
#   curl -fsSL https://bosunmux.app/install.sh | sh
#
# Downloads bosun-host for this computer from dl.bosunmux.app, checks
# its SHA-256 against the release's SHA256SUMS, installs it to
# ~/.local/bin (where the Bosun app looks over SSH), then runs
# `bosun-host setup` (checks, login service, pairing QR).
#
# Environment:
#   BOSUN_VERSION=0.1.0   install that version instead of the latest
#   BOSUN_BIN_DIR=dir     install somewhere else
#   BOSUN_NO_SETUP=1      only install; don't run setup
set -eu

DL="${BOSUN_DL:-https://dl.bosunmux.app/bosun-host}"
BIN_DIR="${BOSUN_BIN_DIR:-$HOME/.local/bin}"

say() { printf '%s\n' "$*"; }
die() { printf 'bosun: %s\n' "$*" >&2; exit 1; }

os=$(uname -s)
arch=$(uname -m)
case "$os-$arch" in
  Darwin-arm64) target=aarch64-apple-darwin ;;
  Darwin-x86_64) target=x86_64-apple-darwin ;;
  Linux-x86_64 | Linux-amd64) target=x86_64-unknown-linux-gnu ;;
  Linux-aarch64 | Linux-arm64) target=aarch64-unknown-linux-gnu ;;
  *) die "no build for $os $arch yet" ;;
esac

if [ -n "${BOSUN_VERSION:-}" ]; then
  base="$DL/v${BOSUN_VERSION#v}"
else
  base="$DL/latest"
fi

command -v curl >/dev/null 2>&1 || die "curl is required"
command -v tar >/dev/null 2>&1 || die "tar is required"
if command -v sha256sum >/dev/null 2>&1; then
  sha() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  die "sha256sum or shasum is required to verify the download"
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM
file="bosun-host-$target.tar.gz"

say "Downloading bosun-host for ${os} ${arch}..."
curl -fsSL "$base/$file" -o "$tmp/$file" || die "download failed: $base/$file"
curl -fsSL "$base/SHA256SUMS" -o "$tmp/SHA256SUMS" || die "download failed: $base/SHA256SUMS"

want=$(awk -v f="$file" '$2 == f || $2 == "*" f { print $1 }' "$tmp/SHA256SUMS")
[ -n "$want" ] || die "$file is not listed in SHA256SUMS"
got=$(sha "$tmp/$file")
[ "$want" = "$got" ] || die "checksum mismatch for $file (expected $want, got $got)"

tar -xzf "$tmp/$file" -C "$tmp"
[ -f "$tmp/bosun-host" ] || die "archive did not contain bosun-host"
mkdir -p "$BIN_DIR"
install -m 0755 "$tmp/bosun-host" "$BIN_DIR/bosun-host" 2>/dev/null || {
  cp "$tmp/bosun-host" "$BIN_DIR/bosun-host"
  chmod 0755 "$BIN_DIR/bosun-host"
}
say "Installed $("$BIN_DIR/bosun-host" --version) to $BIN_DIR/bosun-host"

if [ "$BIN_DIR" != "$HOME/.local/bin" ]; then
  say "Note: the Bosun app looks for bosun-host in ~/.local/bin over SSH; link it there:"
  say "  mkdir -p ~/.local/bin && ln -sf \"$BIN_DIR/bosun-host\" ~/.local/bin/bosun-host"
fi

if [ "${BOSUN_NO_SETUP:-}" = "1" ]; then
  say "Run \`$BIN_DIR/bosun-host setup\` when you're ready."
  exit 0
fi

say ""
# The script itself arrives on stdin (curl | sh): give setup the terminal.
if [ -r /dev/tty ]; then
  exec "$BIN_DIR/bosun-host" setup </dev/tty
else
  exec "$BIN_DIR/bosun-host" setup
fi
