#!/bin/sh
# Install kjarni CLI
# Usage: curl -fsSL https://kjarni.ai/install.sh | sh
#
# Installs the latest release. Set KJARNI_VERSION (e.g. 0.2.6) to pin one, and
# KJARNI_INSTALL_DIR to install somewhere other than ~/.local/bin. The directory
# is added to your shell's PATH unless KJARNI_NO_MODIFY_PATH is set.
set -e

REPO="olafurjohannsson/kjarni"
INSTALL_DIR="${KJARNI_INSTALL_DIR:-$HOME/.local/bin}"

# Detect OS and architecture
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
    Linux)  os="linux" ;;
    Darwin) os="macos" ;;
    *)      echo "Error: unsupported OS: $OS"; exit 1 ;;
esac

case "$ARCH" in
    x86_64|amd64)  arch="x86_64" ;;
    aarch64|arm64) arch="aarch64" ;;
    *)             echo "Error: unsupported architecture: $ARCH"; exit 1 ;;
esac

if [ "$os" = "macos" ] && [ "$arch" = "x86_64" ]; then
    echo "Error: there is no build for Intel Macs, only Apple Silicon."
    exit 1
fi

FILENAME="kjarni-${arch}-${os}.tar.gz"

# releases/latest/download always points at the newest non-prerelease, so this
# script never needs editing for a new version.
if [ -n "$KJARNI_VERSION" ]; then
    TAG="v${KJARNI_VERSION#v}"
    BASE="https://github.com/${REPO}/releases/download/${TAG}"
    echo "Installing kjarni ${TAG} (${arch}-${os})"
else
    BASE="https://github.com/${REPO}/releases/latest/download"
    echo "Installing the latest kjarni (${arch}-${os})"
fi
echo ""

# Check if binary already exists
if command -v kjarni >/dev/null 2>&1; then
    echo "Note: kjarni is already installed at $(command -v kjarni)"
    echo "      This will install to ${INSTALL_DIR}/kjarni"
    echo ""
fi

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

fetch() {
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "$1" -O "$2"
    else
        echo "Error: curl or wget required"
        exit 1
    fi
}

echo "Downloading ${BASE}/${FILENAME}"
fetch "${BASE}/${FILENAME}" "${TMPDIR}/${FILENAME}"

# Verify against the checksums published with the release.
if fetch "${BASE}/SHA256SUMS" "${TMPDIR}/SHA256SUMS" 2>/dev/null; then
    expected="$(grep " ${FILENAME}\$" "${TMPDIR}/SHA256SUMS" | cut -d' ' -f1)"
    if command -v sha256sum >/dev/null 2>&1; then
        actual="$(sha256sum "${TMPDIR}/${FILENAME}" | cut -d' ' -f1)"
    elif command -v shasum >/dev/null 2>&1; then
        actual="$(shasum -a 256 "${TMPDIR}/${FILENAME}" | cut -d' ' -f1)"
    else
        actual=""
    fi
    if [ -z "$expected" ] || [ -z "$actual" ]; then
        echo "Warning: could not verify the checksum; continuing"
    elif [ "$expected" != "$actual" ]; then
        echo "Error: checksum mismatch for ${FILENAME}"
        echo "  expected ${expected}"
        echo "  got      ${actual}"
        exit 1
    fi
else
    echo "Warning: this release has no SHA256SUMS; continuing without verification"
fi

# Extract
tar xzf "${TMPDIR}/${FILENAME}" -C "$TMPDIR"

# Install
mkdir -p "$INSTALL_DIR"
mv "${TMPDIR}/kjarni" "${INSTALL_DIR}/kjarni"
chmod +x "${INSTALL_DIR}/kjarni"

echo ""
echo "Installed $("${INSTALL_DIR}/kjarni" --version) to ${INSTALL_DIR}/kjarni"

# A script run as `curl ... | sh` cannot change the PATH of the shell that started
# it, so the install directory goes into the shell's startup file for every new
# terminal, and this one is told the full path. KJARNI_NO_MODIFY_PATH=1 skips it.
case ":$PATH:" in
    *":${INSTALL_DIR}:"*) on_path=1 ;;
    *)                    on_path=0 ;;
esac

if [ "$on_path" = 0 ]; then
    case "$(basename "${SHELL:-sh}")" in
        zsh)  rc="${ZDOTDIR:-$HOME}/.zshrc"
              line="export PATH=\"${INSTALL_DIR}:\$PATH\"" ;;
        bash) if [ "$os" = "macos" ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi
              line="export PATH=\"${INSTALL_DIR}:\$PATH\"" ;;
        fish) rc="$HOME/.config/fish/conf.d/kjarni.fish"
              line="fish_add_path \"${INSTALL_DIR}\"" ;;
        *)    rc="$HOME/.profile"
              line="export PATH=\"${INSTALL_DIR}:\$PATH\"" ;;
    esac

    echo ""
    if [ -n "$KJARNI_NO_MODIFY_PATH" ]; then
        echo "${INSTALL_DIR} is not on your PATH. Add this line to ${rc}:"
        echo "  ${line}"
    else
        if grep -qsF "$line" "$rc"; then
            echo "${rc} already adds ${INSTALL_DIR} to your PATH."
        else
            mkdir -p "$(dirname "$rc")"
            printf '\n# Added by the kjarni installer\n%s\n' "$line" >> "$rc"
            echo "Added ${INSTALL_DIR} to your PATH in ${rc}."
        fi
        echo "New terminals will find kjarni. In this one, run:"
        echo "  ${INSTALL_DIR}/kjarni --help"
        echo ""
        exit 0
    fi
fi

echo ""
echo "Run 'kjarni --help' to get started"
