#!/usr/bin/env sh
# Paysio CLI installer.
#
#   curl -fsSL https://paysio.com/install.sh | sh
#
# Downloads a standalone binary (no Node required). Set PAYSIO_INSTALL_DIR to
# choose where it lands, or PAYSIO_VERSION to pin a version.
set -eu

CDN="${PAYSIO_CDN:-https://cdn.paysio.com/cli}"
INSTALL_DIR="${PAYSIO_INSTALL_DIR:-$HOME/.paysio/bin}"

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

os="$(uname -s)"
arch="$(uname -m)"

case "$os" in
  Darwin)
    case "$arch" in
      arm64|aarch64) asset="paysio-darwin-arm64" ;;
      x86_64) asset="paysio-darwin-x64" ;;
      *) red "Unsupported macOS architecture: $arch"; exit 1 ;;
    esac
    ;;
  Linux)
    case "$arch" in
      x86_64) asset="paysio-linux-x64" ;;
      *) red "Unsupported Linux architecture: $arch"; exit 1 ;;
    esac
    ;;
  MINGW*|MSYS*|CYGWIN*)
    red "On Windows, install with PowerShell instead:"
    red "  irm https://paysio.com/install.ps1 | iex"
    red "Or use npm:  npm install -g paysio"
    exit 1
    ;;
  *)
    red "Unsupported operating system: $os"
    red "Install with npm instead:  npm install -g paysio"
    exit 1
    ;;
esac

# Resolve the version to install.
#
# We deliberately ask the npm registry rather than downloading the CDN's
# "latest" folder. Version folders are immutable, so the CDN can cache them
# forever and always be right; "latest" is mutable, and a CDN edge that cached
# the previous release keeps handing out the old binary until its TTL expires.
# That actually happened: a released fix sat behind a 4-hour cached "latest".
# Reading the version from npm and then fetching the immutable path removes the
# problem entirely instead of relying on someone remembering to purge a cache.
version="${PAYSIO_VERSION:-}"
if [ -z "$version" ]; then
  dim "Resolving the latest version..."
  version="$(curl -fsSL https://registry.npmjs.org/paysio/latest 2>/dev/null \
    | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
    | head -n 1 || true)"
fi

if [ -n "$version" ]; then
  url="$CDN/$version/$asset"
else
  # npm unreachable (offline, firewall). Fall back to the mutable folder, which
  # is right except in the window right after a release.
  dim "Could not reach the npm registry; falling back to the latest folder."
  version="latest"
  url="$CDN/latest/$asset"
fi

tmp="$(mktemp)"

dim "Downloading $asset ($version)..."
if ! curl -fsSL "$url" -o "$tmp"; then
  rm -f "$tmp"
  red "Download failed: $url"
  red "Install with npm instead:  npm install -g paysio"
  exit 1
fi

mkdir -p "$INSTALL_DIR"
mv "$tmp" "$INSTALL_DIR/paysio"
chmod +x "$INSTALL_DIR/paysio"

green "Installed paysio $version to $INSTALL_DIR/paysio"

# Put it on PATH.
#
# Printing "add this to your profile" and stopping is not enough: the very next
# thing anyone types is `paysio login`, and it fails with "command not found"
# before they have read the message. `curl | sh` cannot prompt (stdin is the
# script), so we append to the profile the way bun, deno and nvm do, guarded by a
# marker so re-running the installer never duplicates the line.
# Set PAYSIO_NO_MODIFY_PATH=1 to skip this entirely.
#
# We write to EVERY startup file the shell might read, not just one, because zsh
# and bash split them by shell type and picking one silently misses the others:
#
#   .zshrc     interactive shells only  -- a terminal window
#   .zprofile  login shells             -- `zsh -l -c`, ssh, some CI runners
#
# Writing only .zshrc (what bun does) means `zsh -l -c 'paysio ...'` still says
# command not found. That matters more here than for a normal tool: this CLI is
# built to be driven by AI agents and scripts, which frequently spawn exactly
# those non-interactive shells.
MARKER="# added by the Paysio CLI installer"

# The profile gets ONE stable line that sources an env file we own. The PATH
# logic itself lives in that env file, so improving it later means rewriting a
# file we control instead of trying to rewrite lines already pasted into
# someone's .zshrc. (rustup does the same thing with ~/.cargo/env, for the same
# reason.) The first version of this installer inlined the logic, and changing
# it turned into a migration problem immediately.
PAYSIO_HOME="$HOME/.paysio"
ENV_FILE="$PAYSIO_HOME/env"
ENV_FISH="$PAYSIO_HOME/env.fish"

posix_line="[ -f \"\$HOME/.paysio/env\" ] && . \"\$HOME/.paysio/env\""
fish_line="test -f \"\$HOME/.paysio/env.fish\"; and source \"\$HOME/.paysio/env.fish\""

mkdir -p "$PAYSIO_HOME"

# REMOVE-then-PREPEND, not skip-if-present.
#
# The obvious "only add it if it is missing" guard is wrong here. In a login
# shell zsh reads .zprofile first (which puts us on PATH) and .zshrc second --
# and .zshrc is where npm/bun/nvm put THEIR bin directories, ahead of ours. A
# skip-if-present guard then does nothing, because the directory is technically
# already on PATH, just no longer first. The result is that a stale
# `npm i -g paysio` keeps winning and the user sees the old version forever.
#
# Stripping our entry and re-prepending gives both properties at once: exactly
# one entry, always first.
#
# Written as an explicit split loop, NOT as "\${PATH//:\$dir:/:}". In that
# substitution form "/" is the delimiter between pattern and replacement, and
# every directory here contains slashes -- bash parses the pattern as just ":"
# and shreds PATH into garbage. The loop below is POSIX, behaves identically in
# bash, zsh and dash, and spawns no subprocess on shell startup.
cat > "$ENV_FILE" <<EOF
# Paysio CLI environment. Managed by the installer - edits will be overwritten.
# Sourced from your shell profile. Puts $INSTALL_DIR first on PATH, exactly once.
__paysio_dir="$INSTALL_DIR"
__paysio_rest="\$PATH"
__paysio_new=""
while [ -n "\$__paysio_rest" ]; do
    __paysio_head="\${__paysio_rest%%:*}"
    case "\$__paysio_rest" in
        *:*) __paysio_rest="\${__paysio_rest#*:}" ;;
        *)   __paysio_rest="" ;;
    esac
    # Drops our own directory (re-added at the front below) and empty entries,
    # which mean "current directory" and should never be on PATH.
    if [ -n "\$__paysio_head" ] && [ "\$__paysio_head" != "\$__paysio_dir" ]; then
        if [ -z "\$__paysio_new" ]; then
            __paysio_new="\$__paysio_head"
        else
            __paysio_new="\$__paysio_new:\$__paysio_head"
        fi
    fi
done
if [ -n "\$__paysio_new" ]; then
    PATH="\$__paysio_dir:\$__paysio_new"
else
    PATH="\$__paysio_dir"
fi
export PATH
unset __paysio_dir __paysio_rest __paysio_new __paysio_head
EOF

cat > "$ENV_FISH" <<EOF
# Paysio CLI environment. Managed by the installer - edits will be overwritten.
if type -q fish_add_path
    fish_add_path --move --prepend "$INSTALL_DIR"
else
    set -gx PATH "$INSTALL_DIR" (string match -v -- "$INSTALL_DIR" \$PATH)
end
EOF

# Match on the source line, not the marker comment, so a profile still carrying
# the older inlined block gets the new line appended after it. Appending later
# means the new logic runs last and wins, which self-heals the old install.
add_to_profile() {
  profile="$1"
  line="$2"
  [ -f "$profile" ] || touch "$profile" 2>/dev/null || return 1
  if grep -qF '.paysio/env' "$profile" 2>/dev/null; then
    return 2 # already sources our env file
  fi
  printf '\n%s\n%s\n' "$MARKER" "$line" >> "$profile" || return 1
  return 0
}

case ":$PATH:" in
  *":$INSTALL_DIR:"*)
    already_on_path=1
    ;;
  *)
    already_on_path=0
    ;;
esac

# Deliberately NOT exiting early when the directory is already on PATH. It being
# on PATH in THIS shell says nothing about whether the profile is set up -- it is
# also true when someone exported it by hand, or when a previous run configured
# .zprofile but not .zshrc. Bailing out here left those machines permanently
# half-configured. Setting up the profile is idempotent, so just always do it.
if [ "${PAYSIO_NO_MODIFY_PATH:-0}" = "1" ]; then
  echo ""
  echo "Add it to your PATH by putting this in your shell profile:"
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
  echo ""
  dim "Next: paysio login"
  exit 0
fi

# $SHELL is the login shell, which is the one whose startup files matter here.
shell_name="$(basename "${SHELL:-}" 2>/dev/null || true)"
profiles=""
export_line="$posix_line"
case "$shell_name" in
  zsh)
    # Both, deliberately: .zshrc for terminal windows, .zprofile for login and
    # non-interactive login shells.
    profiles="${ZDOTDIR:-$HOME}/.zshrc ${ZDOTDIR:-$HOME}/.zprofile"
    ;;
  bash)
    # macOS starts Terminal with a LOGIN shell, which reads .bash_profile and
    # never .bashrc. Linux is the other way round. Write both rather than guess.
    profiles="$HOME/.bash_profile $HOME/.bashrc"
    ;;
  fish)
    profiles="$HOME/.config/fish/config.fish"
    export_line="$fish_line"
    mkdir -p "$HOME/.config/fish" 2>/dev/null || true
    ;;
  *)
    profiles=""
    ;;
esac

if [ -n "$profiles" ]; then
  written="" ; skipped="" ; failed=""
  for profile in $profiles; do
    # `|| rc=$?` is load-bearing. The script runs under `set -e`, and a bare
    # call to a function that returns non-zero aborts immediately -- reading
    # `$?` on the NEXT line is too late. Without this, re-running the installer
    # on an already-configured machine exited 2 right here and never printed the
    # summary or "Next: paysio login", which looked like a broken install.
    rc=0
    add_to_profile "$profile" "$export_line" || rc=$?
    case "$rc" in
      0) written="$written $profile" ;;
      2) skipped="$skipped $profile" ;;
      *) failed="$failed $profile" ;;
    esac
  done

  if [ -n "$written" ]; then
    echo ""
    for p in $written; do green "Added $INSTALL_DIR to your PATH in $p"; done
    echo ""
    echo "Run this once to use paysio in THIS shell:"
    echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
    echo "New shells will pick it up automatically."
  elif [ -n "$skipped" ] && [ "$already_on_path" = "0" ]; then
    echo ""
    echo "Your shell profile is already set up, but $INSTALL_DIR is not on PATH in"
    echo "this shell yet. Run:"
    echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
  elif [ -n "$skipped" ]; then
    echo ""
    dim "Shell profile already set up."
  fi

  if [ -n "$failed" ]; then
    echo ""
    for p in $failed; do echo "Could not write to $p."; done
    echo "Add this to your shell profile by hand:"
    echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
  fi
else
  echo ""
  echo "Add it to your PATH by putting this in your shell profile:"
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
fi

# A previous `npm i -g paysio` or `bun add -g paysio` leaves a second copy on
# PATH, usually EARLIER than ours. The upgrade then looks like it silently did
# nothing: the installer reports the new version, `paysio --version` reports the
# old one, and nothing explains why. Say it plainly instead.
existing="$(command -v paysio 2>/dev/null || true)"
if [ -n "$existing" ] && [ "$existing" != "$INSTALL_DIR/paysio" ]; then
  echo ""
  red "Heads up: another paysio is ahead of this one on your PATH:"
  red "  $existing"
  red "Until it is removed, that copy wins and may report an older version."
  red "Remove it with:  npm uninstall -g paysio   (or: bun remove -g paysio)"
fi

echo ""
dim "Next: paysio login"
