#!/bin/sh
set -e

# Fabric CLI installer
# Usage: curl -fsSL https://fabric.so/cli/install.sh | sh

INSTALL_DIR="${FABRIC_INSTALL_DIR:-$HOME/.fabric/bin}"
BINARY_NAME="fabric"
NODE_MIN_MAJOR=18

# Release artifact URL — update this to point to your GitHub/CDN release.
# The standalone build (npm run build:standalone) produces dist/fabric-standalone.js.
RELEASE_BASE_URL="https://cli.fabric.so"
ARTIFACT_NAME="fabric-standalone.mjs"

# ── Helpers ──────────────────────────────────────────────────────────────────

print_step() { printf '  \033[1;34m→\033[0m %s\n' "$1"; }
print_ok()   { printf '  \033[1;32m✓\033[0m %s\n' "$1"; }
print_err()  { printf '  \033[1;31m✗\033[0m %s\n' "$1" >&2; }

fail() {
  print_err "$1"
  exit 1
}

# ── Node.js check ─────────────────────────────────────────────────────────────

check_node() {
  if ! command -v node >/dev/null 2>&1; then
    fail "Node.js is not installed. Please install Node.js ${NODE_MIN_MAJOR}+ from https://nodejs.org and try again."
  fi
  node_version=$(node --version | sed 's/v//')
  node_major=$(echo "$node_version" | cut -d. -f1)
  if [ "$node_major" -lt "$NODE_MIN_MAJOR" ]; then
    fail "Node.js ${NODE_MIN_MAJOR}+ is required (found v${node_version}). Please upgrade from https://nodejs.org"
  fi
  print_ok "Node.js v${node_version}"
}

# ── Download ──────────────────────────────────────────────────────────────────

download() {
  url="$1"
  dest="$2"
  cache_bust="?v=$(date +%s)"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -H 'Cache-Control: no-cache' -H 'Pragma: no-cache' "${url}${cache_bust}" -o "$dest"
  elif command -v wget >/dev/null 2>&1; then
    wget -q --no-cache -O "$dest" "${url}${cache_bust}"
  else
    fail "Neither curl nor wget found. Please install one and try again."
  fi
}

# ── Install ───────────────────────────────────────────────────────────────────

main() {
  printf '\n\033[1mFabric CLI installer\033[0m\n\n'

  print_step "Checking Node.js..."
  check_node

  print_step "Creating install directory: ${INSTALL_DIR}"
  mkdir -p "$INSTALL_DIR"

  js_dest="${INSTALL_DIR}/${ARTIFACT_NAME}"
  wrapper_dest="${INSTALL_DIR}/${BINARY_NAME}"

  print_step "Downloading Fabric CLI..."
  download "${RELEASE_BASE_URL}/${ARTIFACT_NAME}" "$js_dest"
  chmod +x "$js_dest"

  # Write a wrapper script so users just run `fabric` without specifying node.
  cat > "$wrapper_dest" <<WRAPPER
#!/bin/sh
exec node "${js_dest}" "\$@"
WRAPPER
  chmod +x "$wrapper_dest"

  print_ok "Installed to ${wrapper_dest}"

  # ── PATH setup ──────────────────────────────────────────────────────────────

  case ":${PATH}:" in
    *":${INSTALL_DIR}:"*)
      # Already in PATH
      ;;
    *)
      print_step "Adding ${INSTALL_DIR} to PATH..."
      shell_rc=""
      fish_config="$HOME/.config/fish/config.fish"
      if [ -n "$ZSH_VERSION" ] || [ "$(basename "$SHELL")" = "zsh" ]; then
        shell_rc="$HOME/.zshrc"
      elif [ "$(basename "$SHELL")" = "fish" ]; then
        shell_rc="__fish__"
      elif [ -n "$BASH_VERSION" ] || [ "$(basename "$SHELL")" = "bash" ]; then
        if [ -f "$HOME/.bashrc" ]; then
          shell_rc="$HOME/.bashrc"
        elif [ -f "$HOME/.bash_profile" ]; then
          shell_rc="$HOME/.bash_profile"
        elif [ "$(uname)" = "Darwin" ]; then
          shell_rc="$HOME/.bash_profile"
        else
          shell_rc="$HOME/.bashrc"
        fi
      fi

      if [ "$shell_rc" = "__fish__" ]; then
        mkdir -p "$(dirname "$fish_config")"
        if ! grep -qF "$INSTALL_DIR" "$fish_config" 2>/dev/null; then
          printf '\n# Fabric CLI\nfish_add_path %s\n' "$INSTALL_DIR" >> "$fish_config"
          print_ok "Added to ${fish_config}"
        fi
        printf '\n  \033[33mRun \033[1msource %s\033[0m\033[33m or open a new terminal to apply.\033[0m\n' "$fish_config"
      elif [ -n "$shell_rc" ]; then
        export_line="export PATH=\"${INSTALL_DIR}:\$PATH\""
        if ! grep -qF "$INSTALL_DIR" "$shell_rc" 2>/dev/null; then
          printf '\n# Fabric CLI\n%s\n' "$export_line" >> "$shell_rc"
          print_ok "Added to ${shell_rc}"
        fi
        # shellcheck disable=SC1090
        printf '\n  \033[33mRun \033[1msource %s\033[0m\033[33m or open a new terminal to apply.\033[0m\n' "$shell_rc"
      else
        printf '\n  \033[33mAdd this to your shell config:\033[0m\n  export PATH="%s:$PATH"\n' "$INSTALL_DIR"
      fi
      ;;
  esac

  printf '\n\033[1;32mDone!\033[0m Run \033[1mfabric\033[0m to get started.\n\n'
}

main
