#!/usr/bin/env bash
#
# Literal Security — universal installer.
# Usage:
#   curl -fsSL https://literalsec.com/install | bash
#
# Or, with a token pre-set:
#   LITERALSEC_TOKEN=lsec_... bash <(curl -fsSL https://literalsec.com/install)
#
# Installs the `literalsec` CLI to /usr/local/bin (falls back to ~/.local/bin
# if /usr/local/bin isn't writable). Requires Node 18+ for the built-in
# fetch API.

set -e

# Two distinct hosts in our cloud setup:
#   * STATIC_URL  — marketing landing. Serves /cli.js, /install, /docs.
#                   Defaults to literalsec.com (correct for cloud users).
#   * (CLI runtime) — after install, the CLI itself calls /v1/* on a separate
#                     API host. It reads LITERALSEC_API_URL for that, defaulting
#                     to api.literalsec.com inside cli.js.
# Don't conflate the two. Self-hosters can override LITERALSEC_STATIC_URL here
# without breaking cli.js's API targeting.
STATIC_URL="${LITERALSEC_STATIC_URL:-${LITERALSEC_API_URL:-https://literalsec.com}}"
CLI_NAME="literalsec"

# 1. Verify prereqs
if ! command -v node >/dev/null 2>&1; then
  echo "✗ Node 18+ is required. Install from https://nodejs.org and re-run." >&2
  exit 1
fi
NODE_MAJOR=$(node -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')
if [ "$NODE_MAJOR" -lt 18 ]; then
  echo "✗ Node 18+ required (you have $(node -v))." >&2
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  echo "✗ curl is required for download." >&2
  exit 1
fi

# 2. Decide install path
INSTALL_DIR="/usr/local/bin"
if [ ! -w "$INSTALL_DIR" ] && ! command -v sudo >/dev/null 2>&1; then
  INSTALL_DIR="${HOME}/.local/bin"
elif [ ! -w "$INSTALL_DIR" ]; then
  echo "  /usr/local/bin requires sudo; using $HOME/.local/bin instead."
  INSTALL_DIR="${HOME}/.local/bin"
fi
mkdir -p "$INSTALL_DIR"
CLI_PATH="${INSTALL_DIR}/${CLI_NAME}"

# 3. Download
echo "→ Downloading literalsec CLI from ${STATIC_URL}/cli.js …"
TMP="$(mktemp)"
if ! curl -fsSL "${STATIC_URL}/cli.js" -o "$TMP"; then
  echo "✗ Download failed." >&2
  rm -f "$TMP"
  exit 1
fi
mv "$TMP" "$CLI_PATH"
chmod +x "$CLI_PATH"
echo "✓ Installed: $CLI_PATH"

# 4. PATH check — when the install dir isn't on PATH (common on Git Bash for
#    Windows, fresh Linux accounts without a populated ~/.bashrc, etc.) we
#    auto-append the export line to the user's shell rc. Idempotent — if the
#    line is already present, we skip. Falls back to printing instructions
#    if we can't detect a writable rc file.
case ":$PATH:" in
  *":$INSTALL_DIR:"*)
    ;;
  *)
    EXPORT_LINE="export PATH=\"$INSTALL_DIR:\$PATH\""
    # Best-guess of which rc file actually loads for the user's shell. We try
    # the active SHELL first, then fall back to the common ones in order.
    RC_CANDIDATES=""
    case "${SHELL:-}" in
      */zsh)  RC_CANDIDATES="$HOME/.zshrc $HOME/.zprofile" ;;
      */bash) RC_CANDIDATES="$HOME/.bashrc $HOME/.bash_profile $HOME/.profile" ;;
      *)      RC_CANDIDATES="$HOME/.bashrc $HOME/.bash_profile $HOME/.zshrc $HOME/.profile" ;;
    esac
    RC_TOUCHED=""
    for RC in $RC_CANDIDATES; do
      [ -e "$RC" ] || continue
      # Already added by a prior install — don't double-write.
      if grep -Fq "$INSTALL_DIR" "$RC" 2>/dev/null; then
        RC_TOUCHED="$RC (already configured)"
        break
      fi
      # Write only if we can. Append in a marked block so the user can find +
      # remove it later if they want.
      if [ -w "$RC" ] || { [ ! -e "$RC" ] && [ -w "$(dirname "$RC")" ]; }; then
        {
          printf '\n# Added by literalsec installer — adds the CLI to PATH\n'
          printf '%s\n' "$EXPORT_LINE"
        } >> "$RC"
        RC_TOUCHED="$RC"
        break
      fi
    done
    echo ""
    if [ -n "$RC_TOUCHED" ]; then
      echo "✓ PATH updated in $RC_TOUCHED"
      echo "  Run this once in your current shell (or open a new terminal):"
      echo ""
      echo "    $EXPORT_LINE"
      echo ""
    else
      echo "  Note: $INSTALL_DIR is not on your PATH and we couldn't find a"
      echo "  writable shell-rc to append to. Add this line yourself:"
      echo ""
      echo "    $EXPORT_LINE"
      echo ""
      echo "  …to whichever of these your shell loads:"
      echo "    ~/.bashrc · ~/.zshrc · ~/.bash_profile · ~/.profile"
      echo ""
    fi
    ;;
esac

# 5. Optionally save token
if [ -n "${LITERALSEC_TOKEN:-}" ]; then
  mkdir -p "$HOME/.literalsec"
  printf '%s\n' "$LITERALSEC_TOKEN" > "$HOME/.literalsec/token"
  chmod 600 "$HOME/.literalsec/token"
  echo "✓ Token saved to $HOME/.literalsec/token (chmod 600)"
fi

echo ""
echo "Next steps:"
echo "  1. Get a token (free):       https://app.literalsec.com/dashboard"
if [ -z "${LITERALSEC_TOKEN:-}" ]; then
  echo "  2. Authenticate:             literalsec login"
fi
echo "  3. Wire your project:        cd <your-project> && literalsec init"
echo ""
echo "  Manual scan:                 literalsec scan path/to/file.ts"
echo "  See what's installed here:   literalsec status"
echo ""
echo "Docs: ${STATIC_URL}/docs"
