#!/usr/bin/env bash
set -euo pipefail

# LuisForge CLI installer.
# Usage: curl -fsSL https://luisforge.pages.dev/install.sh | bash

if [ "$(id -u)" -eq 0 ] || [ -n "${SUDO_USER:-}" ]; then
  echo "==> Don't run this with sudo (or as root)."
  echo "    forge is installed per-user into ~/.local/bin — running as root would"
  echo "    install it into root's home instead of yours, and you'd need sudo every"
  echo "    time you ran 'forge' afterward. Re-run as your normal user:"
  echo ""
  echo "      curl -fsSL https://luisforge.pages.dev/install.sh | bash"
  echo ""
  exit 1
fi

INSTALL_DIR="$HOME/.local/bin"
mkdir -p "$INSTALL_DIR"

echo "==> Downloading forge to $INSTALL_DIR/forge"
curl -fsSL https://luisforge.pages.dev/forge.py -o "$INSTALL_DIR/forge"
chmod +x "$INSTALL_DIR/forge"

echo "==> Downloading codey to $INSTALL_DIR/codey"
curl -fsSL https://luisforge.pages.dev/codey.py -o "$INSTALL_DIR/codey"
chmod +x "$INSTALL_DIR/codey"

# Detect the user's actual login shell rather than the shell running this
# script (curl | bash always runs under bash regardless of $SHELL).
shell_name="$(basename "${SHELL:-bash}")"
case "$shell_name" in
  zsh)  rc_file="$HOME/.zshrc" ;;
  bash) rc_file="$HOME/.bashrc" ;;
  *)    rc_file="$HOME/.profile" ;;
esac

if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  if [ -f "$rc_file" ] && grep -qF "$INSTALL_DIR" "$rc_file" 2>/dev/null; then
    echo "==> $INSTALL_DIR already on PATH via $rc_file"
  else
    echo "==> Adding $INSTALL_DIR to PATH in $rc_file (detected shell: $shell_name)"
    { echo ""; echo "# added by LuisForge install.sh"; echo "export PATH=\"$INSTALL_DIR:\$PATH\""; } >> "$rc_file"
    echo "==> Restart your shell (or run: source $rc_file) to use 'forge'"
  fi
else
  echo "==> $INSTALL_DIR already on PATH"
fi

echo "==> Installed. Try: forge auth signup"
echo "==> Also installed: codey (chat with LuisCodey from the terminal — codey <owner/repo>)"
