#!/bin/sh
# Install termosh for the current user.
#
#   curl -fsSL https://term.const.net/termosh/install.sh | sh
#   curl -fsSL https://term.const.net/termosh/install.sh | TERMOSH_VERSION=<x.y.z> sh
#
# Picks the build for this machine (a gzipped binary), checks it against the release's SHA256SUMS,
# unpacks it, and puts it in
# ~/.local/bin (or $TERMOSH_INSTALL_DIR). No root needed, nothing outside that directory changes.
# It ends by printing the FULL PATH to give Term's "mosh-server command": a non-interactive SSH
# login (which is how mosh starts its server) often does not have ~/.local/bin on its PATH, so a
# bare `termosh` there would not be found.
#
# Which version it installs: $TERMOSH_VERSION if set; otherwise the version release.sh stamped
# into this copy (every copy shipped in a dist/<version>/ is pinned to its own release, so a
# release can never install some OTHER release); otherwise — the unstamped copy in the repo —
# whatever <base>/LATEST names.
set -eu

base="${TERMOSH_BASE_URL:-https://term.const.net/termosh}"
dir="${TERMOSH_INSTALL_DIR:-$HOME/.local/bin}"
version="${TERMOSH_VERSION:-0.6.1}"

case "$(uname -s)" in
    Linux) os=linux ;;
    Darwin) os=macos ;;
    *) echo "termosh: no build for $(uname -s) yet" >&2; exit 1 ;;
esac
case "$(uname -m)" in
    x86_64 | amd64) arch=x86_64 ;;
    aarch64 | arm64) [ "$os" = macos ] && arch=arm64 || arch=aarch64 ;;
    *) echo "termosh: no build for $(uname -m) yet" >&2; exit 1 ;;
esac

fetch() { # url, file
    if command -v curl >/dev/null; then curl -fsSL "$1" -o "$2"
    elif command -v wget >/dev/null; then wget -qO "$2" "$1"
    else echo "termosh: needs curl or wget" >&2; exit 1
    fi
}

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

if [ -z "$version" ]; then
    fetch "$base/LATEST" "$tmp/LATEST" || true
    version="$(tr -d ' \t\r\n' < "$tmp/LATEST" 2>/dev/null || true)"
fi
if [ -z "$version" ]; then
    echo "termosh: no version: set TERMOSH_VERSION=<x.y.z>, or publish $base/LATEST" >&2
    exit 1
fi

asset="termosh-$version-$os-$arch.gz"
fetch "$base/$version/$asset" "$tmp/$asset"
fetch "$base/$version/SHA256SUMS" "$tmp/SHA256SUMS"

want="$(grep " $asset\$" "$tmp/SHA256SUMS" | cut -d' ' -f1)"
if command -v sha256sum >/dev/null; then got="$(sha256sum "$tmp/$asset" | cut -d' ' -f1)"
else got="$(shasum -a 256 "$tmp/$asset" | cut -d' ' -f1)"
fi
if [ -z "$want" ] || [ "$want" != "$got" ]; then
    echo "termosh: checksum mismatch for $asset; not installed" >&2
    exit 1
fi

gzip -dc "$tmp/$asset" > "$tmp/termosh"
mkdir -p "$dir"
install -m 755 "$tmp/termosh" "$dir/termosh"
"$dir/termosh" --version
echo
echo "Installed: $dir/termosh"
echo "In Term, set this host's Mosh options > mosh-server command to:"
echo "    $dir/termosh"
