#!/bin/sh
# Spwn installer, https://spwn.sh
# Usage: curl -fsSL https://spwn.sh/install.sh | bash
#        curl -fsSL https://spwn.sh/install.sh | bash -s -- [--no-init] [station init's arguments]
#
# Installs, from one release of github.com/jterrazz/spwn, into ~/.local/bin:
#   spwn      (linked as spwn-agents)
#   station   (linked as spwn-machines), where the release has a build for this platform
# and writes to your shell's profile, once each, under the marker below:
#   the PATH line, and the aliases `agents` and `machines`.
# and records where station went, in $XDG_STATE_HOME (else ~/.local/state)/station/installed.json,
# for an app started outside your shell, which sees neither your PATH nor SPWN_INSTALL_DIR;
# a record that cannot be written is a warning, the install stands.
# Every binary is checked against the release's checksums.txt before any is installed.
# Where station was installed and a terminal is there, the script then hands the terminal to
# `station init`, passing it its own arguments (--name, --machinefile); with --no-init, or with
# no terminal (CI, a pipe), it prints that command among the next steps instead.
#
# Environment:
#   SPWN_VERSION      a tag to install (default: the newest release)
#   SPWN_INSTALL_DIR  where the binaries go (default: ~/.local/bin)

set -eu

INIT=true
for arg in "$@"; do
    shift
    case "$arg" in
        --no-init) INIT=false ;;
        *) set -- "$@" "$arg" ;;
    esac
done

REPO="jterrazz/spwn"
INSTALL_DIR="${SPWN_INSTALL_DIR:-$HOME/.local/bin}"
MARKER="# Added by spwn installer"
# shellcheck disable=SC2016 # the line is written to the profile unexpanded
PATH_EXPORT='export PATH="$HOME/.local/bin:$PATH"'

fail() {
    echo "Error: $1" >&2
    exit 1
}

case "$INSTALL_DIR" in
    *[[:cntrl:]]*) fail "the install path holds a control character, nothing installed" ;;
esac

need() {
    command -v "$1" >/dev/null 2>&1 || fail "$1 is required"
}

sha256_of() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{ print $1 }'
    else
        shasum -a 256 "$1" | awk '{ print $1 }'
    fi
}

# The hash checksums.txt gives an asset, empty when it lists none.
listed() {
    awk -v asset="$1" '$2 == asset || $2 == "*" asset { print $1; exit }' "$WORK/checksums.txt"
}

# Downloads an asset the release lists, and refuses it unless its hash is the listed one.
fetch() {
    expected=$(listed "$1")
    [ -n "$expected" ] || fail "checksums.txt has no line for $1, nothing installed"
    echo "Downloading $1..."
    curl -fsSL "${BASE}/$1" -o "$WORK/$1" || fail "could not download $1, nothing installed"
    [ "$(sha256_of "$WORK/$1")" = "$expected" ] || fail "$1 does not match its checksum, nothing installed"
}

# Puts a binary in place under its name: copied beside it, then renamed over it, so a
# running or signed binary is replaced by a new file, never rewritten in place.
place() {
    STAGED="$INSTALL_DIR/.$2.$$"
    cp "$1" "$STAGED"
    chmod 755 "$STAGED"
    mv -f "$STAGED" "$INSTALL_DIR/$2"
    STAGED=""
}

# The profile the user's shell reads: zsh's .zshrc, bash's own file, else the first that
# exists, else ~/.profile.
profile_of() {
    case "${SHELL:-}" in
        */zsh)
            echo "${ZDOTDIR:-$HOME}/.zshrc"
            return
            ;;
        */bash)
            if [ "$OS" = linux ]; then
                echo "$HOME/.bashrc"
                return
            fi
            set -- "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"
            ;;
        *)
            set -- "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"
            ;;
    esac
    for candidate in "$@"; do
        if [ -f "$candidate" ]; then
            echo "$candidate"
            return
        fi
    done
    echo "$HOME/.profile"
}

# Appends one line to the profile unless the profile already holds it.
add_line() {
    if ! grep -qxF "$2" "$1" 2>/dev/null; then
        if [ -s "$1" ] && [ -n "$(tail -c 1 "$1")" ]; then
            echo "" >>"$1"
        fi
        if ! grep -qxF "$MARKER" "$1" 2>/dev/null; then
            printf '\n%s\n' "$MARKER" >>"$1"
        fi
        printf '%s\n' "$2" >>"$1"
        echo "  Added to $1: $2"
    fi
}

# The words given, each as a shell reads it back: bare when it is safe, else single-quoted.
quoted() {
    for word in "$@"; do
        case "$word" in
            "" | *[!A-Za-z0-9_./:=@%+,-]*) printf " '%s'" "$(printf '%s' "$word" | sed "s/'/'\\\\''/g")" ;;
            *) printf ' %s' "$word" ;;
        esac
    done
}

json_escape() {
    printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

# Writes the install record under the state root: a temp file beside it, then renamed over it.
# The record's contract is owned by the engine's API description in the spwn repo (packages/api, under machines/).
record_install() {
    case "${XDG_STATE_HOME:-}" in
        /*) state="$XDG_STATE_HOME" ;;
        *) state="$HOME/.local/state" ;;
    esac
    bin=$(cd "$INSTALL_DIR" && pwd) || return 1
    at=$(date -u +%Y-%m-%dT%H:%M:%SZ) && [ -n "$at" ] || return 1
    mkdir -p "$state/station" || return 1
    STAGED="$state/station/.installed.json.$$"
    printf '{"v":1,"at":"%s","executable":"%s","version":"%s"}\n' \
        "$at" "$(json_escape "$bin/station")" "$(json_escape "$VERSION")" >"$STAGED" || return 1
    chmod 644 "$STAGED" || return 1
    mv -f "$STAGED" "$state/station/installed.json" || return 1
    STAGED=""
}

need curl
need tar
need awk
command -v sha256sum >/dev/null 2>&1 || need shasum

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$OS" in
    linux | darwin) ;;
    *) fail "unsupported OS: $OS" ;;
esac

ARCH=$(uname -m)
case "$ARCH" in
    x86_64 | amd64) ARCH="amd64" ;;
    arm64 | aarch64) ARCH="arm64" ;;
    *) fail "unsupported architecture: $ARCH" ;;
esac

# The newest entry of the release list is taken, whether or not it is flagged pre-release.
VERSION="${SPWN_VERSION:-}"
if [ -z "$VERSION" ]; then
    echo "Detecting the newest release..."
    VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases?per_page=1" |
        sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n 1)
fi
[ -n "$VERSION" ] || fail "could not detect a release, see https://github.com/${REPO}/releases"
echo "Version: ${VERSION}"

BASE="https://github.com/${REPO}/releases/download/${VERSION}"
STAGED=""
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"; [ -z "$STAGED" ] || rm -f "$STAGED"' EXIT
trap 'exit 130' INT TERM HUP

curl -fsSL "${BASE}/checksums.txt" -o "$WORK/checksums.txt" ||
    fail "release ${VERSION} has no checksums.txt"

SPWN_ASSET="spwn_${OS}_${ARCH}.tar.gz"
STATION_ASSET="station-${OS}-${ARCH}"
STATION=false
[ -z "$(listed "$STATION_ASSET")" ] || STATION=true

fetch "$SPWN_ASSET"
mkdir -p "$WORK/spwn"
tar -xzf "$WORK/${SPWN_ASSET}" -C "$WORK/spwn"
[ -f "$WORK/spwn/spwn" ] || fail "${SPWN_ASSET} holds no spwn binary, nothing installed"
if [ "$STATION" = true ]; then
    fetch "$STATION_ASSET"
fi

mkdir -p "$INSTALL_DIR"
place "$WORK/spwn/spwn" spwn
ln -sf spwn "$INSTALL_DIR/spwn-agents"
echo "  ✓ spwn ${VERSION} in ${INSTALL_DIR}, also as spwn-agents"
if [ "$STATION" = true ]; then
    place "$WORK/${STATION_ASSET}" station
    ln -sf station "$INSTALL_DIR/spwn-machines"
    echo "  ✓ station ${VERSION} in ${INSTALL_DIR}, also as spwn-machines"
else
    echo "  - station: ${VERSION} has no build for ${OS}/${ARCH}, skipped"
fi

RC=$(profile_of)
case ":${PATH:-}:" in
    *":${INSTALL_DIR}:"*) ;;
    *)
        if [ "$INSTALL_DIR" = "$HOME/.local/bin" ]; then
            add_line "$RC" "$PATH_EXPORT"
        else
            add_line "$RC" "export PATH=\"${INSTALL_DIR}:\$PATH\""
        fi
        ;;
esac
add_line "$RC" "alias agents='spwn-agents'"
if [ "$STATION" = true ]; then
    add_line "$RC" "alias machines='spwn-machines'"
fi

if [ "$STATION" = true ]; then
    record_install || echo "Warning: could not record where station was installed; the install stands" >&2
fi

RUN_INIT=false
if [ "$STATION" = true ] && [ "$INIT" = true ] && [ -t 1 ] && (: </dev/tty) 2>/dev/null; then
    RUN_INIT=true
fi
INIT_ARGS=$(quoted "$@")

echo ""
echo "  Open a new terminal (or run: . ${RC}), then:"
echo "    agents auth        # check your agent runtime sign-in"
echo "    agents init        # a project and its first agent, neo"
if [ "$STATION" = true ] && [ "$RUN_INIT" = false ]; then
    printf '    %-18s # %s\n' "machines init${INIT_ARGS}" "set this computer up for Machines"
fi
echo ""
echo "  Agents needs Docker running (Docker Desktop or OrbStack)."
echo ""

if [ "$RUN_INIT" = true ]; then
    echo "  Setting this computer up for Machines: station init${INIT_ARGS}"
    echo ""
    status=0
    "$INSTALL_DIR/station" init "$@" </dev/tty || status=$?
    if [ "$status" -ne 0 ]; then
        echo "Warning: station init exited ${status}; the install stands, run it again: machines init${INIT_ARGS}" >&2
        exit "$status"
    fi
fi
