#!/bin/sh
# Backboard CLI installer (native binary)
# Usage: curl -fsSL http://app.backboard.io/api/cli | bash
set -eu

API_BASE="http://app.backboard.io/api"
INVITE_REQUIRED="0"
CODE=""

red()   { printf '\033[31m%s\033[0m\n' "$1" >&2; }
cyan()  { printf '\033[36m%s\033[0m\n' "$1"; }
green() { printf '\033[32m%s\033[0m\n' "$1"; }

case "$(uname -s)" in
    Darwin)
        # `uname -m` reports the *current process* arch, which is
        # ``x86_64`` whenever the shell is running under Rosetta (a
        # common setup). The machine underneath may still be Apple
        # Silicon, and our arm64 binary runs there natively, so trust
        # the hardware probe (`hw.optional.arm64` is 1 on every Apple
        # Silicon Mac) over the translated process arch. Genuine Intel
        # Macs fall through to the x86_64 build.
        if [ "$(uname -m)" = "arm64" ] || [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then
            PLATFORM="macos-arm64"
        else
            PLATFORM="macos-x64"
        fi
        ;;
    *)
        red "error: unsupported OS \"$(uname -s)\" — the native binary is for macOS and Windows only."
        exit 1
        ;;
esac

if [ "$INVITE_REQUIRED" = "1" ] && [ -z "$CODE" ]; then
    printf 'Enter your invite code: '
    read CODE < /dev/tty
fi

INSTALL_DIR="${BACKBOARD_INSTALL:-$HOME/.backboard}/bin"
BINARY="$INSTALL_DIR/backboard"
URL="$API_BASE/cli/download/$PLATFORM"
if [ -n "$CODE" ]; then
    URL="$URL?code=$CODE"
fi

mkdir -p "$INSTALL_DIR"
cyan "  downloading backboard ($PLATFORM)..."
if ! curl -fsSL "$URL" -o "$BINARY.tmp"; then
    red "error: download failed (invalid invite code, or binary not available for $PLATFORM)."
    rm -f "$BINARY.tmp"
    exit 1
fi
chmod +x "$BINARY.tmp"
mv "$BINARY.tmp" "$BINARY"

# Pick the rc files this user's shell actually reads. zsh on macOS
# reads .zshrc for interactive shells and .zprofile for login shells
# (a fresh Terminal.app window is a login shell), so write both —
# otherwise a new window still can't find `backboard`.
case "${SHELL:-}" in
    *zsh)  RC_FILES="$HOME/.zshrc $HOME/.zprofile"; RC="$HOME/.zshrc" ;;
    *bash) RC_FILES="$HOME/.bashrc $HOME/.bash_profile"; RC="$HOME/.bashrc" ;;
    *)     RC_FILES="$HOME/.profile"; RC="$HOME/.profile" ;;
esac

for rc in $RC_FILES; do
    if ! grep -q '.backboard/bin' "$rc" 2>/dev/null; then
        printf '\nexport PATH="%s:$PATH"\n' "$INSTALL_DIR" >> "$rc"
    fi
done

green "  installed -> $BINARY"

# A piped installer runs in a CHILD shell, so it can't mutate the PATH
# of the terminal the user is sitting in — editing rc files only helps
# FUTURE shells. To make a bare `backboard` work right now (no `source`,
# no new terminal), drop a symlink into the first writable, non-system
# directory that's already on the current $PATH. The child inherits the
# parent's $PATH, so this is the same set the parent resolves against.
RESIDENT=""
case ":$PATH:" in
    *":$INSTALL_DIR:"*) RESIDENT="$BINARY" ;;
    *)
        OLD_IFS="$IFS"
        IFS=":"
        for dir in $PATH; do
            IFS="$OLD_IFS"
            { [ -n "$dir" ] && [ -d "$dir" ] && [ -w "$dir" ]; } || { IFS=":"; continue; }
            # Never our own dir (self-referential link) and never system
            # dirs (fighting the OS/package managers breaks other tools).
            case "$dir" in
                "$INSTALL_DIR"|/bin|/sbin|/usr/bin|/usr/sbin|/var/*|/etc/*) IFS=":"; continue ;;
            esac
            # Don't clobber a real `backboard` from another tool, but do
            # replace a symlink (ours from a prior install, or a stale one).
            if [ -e "$dir/backboard" ] && [ ! -L "$dir/backboard" ]; then IFS=":"; continue; fi
            if ln -sf "$BINARY" "$dir/backboard" 2>/dev/null; then
                RESIDENT="$dir/backboard"
                cyan "  linked $dir/backboard (already on your PATH)"
                break
            fi
            IFS=":"
        done
        IFS="$OLD_IFS"
        ;;
esac

if [ -n "$RESIDENT" ]; then
    printf '  run: \033[36mbackboard\033[0m\n'
else
    # No writable PATH dir — the rc edit above still fixes future shells.
    printf '  added %s to PATH in %s\n' "$INSTALL_DIR" "$RC"
    printf '  run it now with:  \033[36msource %s && backboard\033[0m\n' "$RC"
    printf '  (or open a new terminal and run \033[36mbackboard\033[0m)\n'
fi
