#!/usr/bin/env sh
set -eu

BASE_URL="${CHECKHERE_BASE_URL:-https://checkhere.page}"
if [ -n "${CHECKHERE_INSTALL_DIR:-}" ]; then
  BIN_DIR="$CHECKHERE_INSTALL_DIR"
elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  BIN_DIR="/usr/local/bin"
elif [ -d /opt/homebrew/bin ] && [ -w /opt/homebrew/bin ]; then
  BIN_DIR="/opt/homebrew/bin"
else
  BIN_DIR="$HOME/.checkhere/bin"
fi
BIN_PATH="$BIN_DIR/checkhere"

mkdir -p "$BIN_DIR"
curl -fsSL "$BASE_URL/cli/checkhere.js" -o "$BIN_PATH"
chmod +x "$BIN_PATH"

case ":${PATH:-}:" in
  *":$BIN_DIR:"*) ;;
  *)
    SHELL_RC=""
    if [ -n "${ZSH_VERSION:-}" ]; then SHELL_RC="$HOME/.zshrc"; fi
    if [ -z "$SHELL_RC" ] && [ -n "${BASH_VERSION:-}" ]; then SHELL_RC="$HOME/.bashrc"; fi
    if [ -n "$SHELL_RC" ]; then
      printf '\nexport PATH="$HOME/.checkhere/bin:$PATH"\n' >> "$SHELL_RC"
    fi
    ;;
esac

echo "CheckHere installed at $BIN_PATH"
case ":${PATH:-}:" in
  *":$BIN_DIR:"*) ;;
  *) echo "Add this to PATH if checkhere is not found: export PATH=\"$BIN_DIR:\$PATH\"" ;;
esac
echo "Run: checkhere https://your-site.com"
