#!/bin/sh
# Installs kxw, the KnowxWorks desktop sync client, into ~/.local/bin (or $KXW_INSTALL_DIR).
#   curl -fsSL https://www.knowxworks.com/install.sh | sh
# Needs Node.js 22 or newer. Nothing else is changed on your computer.
set -eu
if ! command -v node >/dev/null 2>&1; then
  echo "kxw needs Node.js 22 or newer. Install it from https://nodejs.org and run this again." >&2
  exit 1
fi
major=$(node -p 'process.versions.node.split(".")[0]')
if [ "$major" -lt 22 ]; then
  echo "kxw needs Node.js 22 or newer; this computer has $(node -v)." >&2
  exit 1
fi
dir="${KXW_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$dir"
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
curl -fsSL "${KXW_DOWNLOAD_URL:-https://www.knowxworks.com/kxw.mjs}" -o "$tmp"
if ! head -n 1 "$tmp" | grep -q '^#!/usr/bin/env node'; then
  echo "The download didn't look right; nothing was installed." >&2
  exit 1
fi
chmod 755 "$tmp"
mv "$tmp" "$dir/kxw"
trap - EXIT
echo "Installed kxw $("$dir/kxw" --version) to $dir/kxw"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "Add it to your PATH:  echo 'export PATH=\"$dir:\$PATH\"' >> ~/.zshrc && exec \$SHELL" ;;
esac
echo
echo "Next, with your vault name from KnowxWorks › Settings › Sync:"
echo "  kxw login --vault <vault>"
echo "  kxw init ~/path/to/your/vault --vault <vault>"
echo "  kxw sync ~/path/to/your/vault"
