#!/usr/bin/env bash
# Meshbell bridge installer bootstrap.
#
#   curl -fsSL https://meshbell.com/install.sh | bash
#
# Downloads the bridge package from meshbell.com, checks its integrity, and hands
# off to the package's own install.sh (which sets up the service: systemd on
# Linux, launchd on macOS, and refuses to disturb anything it does not own).
# Every flag you pass lands in that inner installer unchanged.
#
# The checksum comes from the same host as the package, so it catches corruption
# and truncation, not a compromised host. If you want provenance, read this file
# before piping it, and the package's install.sh after download; both are short.
set -euo pipefail

BASE="${MESHBELL_BASE_URL:-https://meshbell.com}"
PKG="meshbell-bridge.tar.gz"

say() { printf '==> %s\n' "$*"; }

command -v curl >/dev/null 2>&1 || { echo "!! curl is required" >&2; exit 1; }
command -v tar >/dev/null 2>&1 || { echo "!! tar is required" >&2; exit 1; }

sha_check() {
  # Linux ships sha256sum; macOS ships shasum.
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum -c "$1"
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 -c "$1"
  else
    echo "!! neither sha256sum nor shasum found; cannot verify the download" >&2
    exit 1
  fi
}

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
cd "$WORK"

say "downloading $BASE/get/$PKG"
# Accept-Encoding pinned to identity: the CDN otherwise transcodes the gzip
# body in flight and the checksum can never match the published one.
curl -fsSL -H 'Accept-Encoding: identity' "$BASE/get/$PKG" -o "$PKG"
curl -fsSL -H 'Accept-Encoding: identity' "$BASE/get/$PKG.sha256" -o "$PKG.sha256"

say "verifying checksum"
sha_check "$PKG.sha256"

tar -xzf "$PKG"
say "installed package version: $(cat meshbell-bridge/VERSION 2>/dev/null || echo unknown)"

exec bash meshbell-bridge/install.sh "$@"
