#!/usr/bin/env bash
# clauth installer
set -e

REPO="https://github.com/LIFEAI/clauth.git"
DIR="$HOME/.clauth"

# Check git
if ! command -v git &>/dev/null; then
  echo ""; echo "  x git is required."
  echo "    Install git from https://git-scm.com then re-run this script."; echo ""
  exit 1
fi

# Check Node
if ! command -v node &>/dev/null; then
  echo ""; echo "  x Node.js v18+ is required."
  echo "    Install from https://nodejs.org then re-run this script."; echo ""
  exit 1
fi

# Check cloudflared (soft warning)
if ! command -v cloudflared &>/dev/null; then
  echo "  Note: cloudflared not found. Install after setup for claude.ai web integration."
  if [[ "$OSTYPE" == "darwin"* ]]; then
    echo "        brew install cloudflare/cloudflare/cloudflared"
  else
    echo "        https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
  fi
  echo ""
fi

# Clone or update
if [ -d "$DIR/.git" ]; then
  echo "  Updating clauth..."; cd "$DIR" && git pull --quiet
else
  echo "  Cloning clauth..."; git clone --quiet "$REPO" "$DIR"
fi

# Run compiled bootstrap
UNAME=$(uname -s | tr '[:upper:]' '[:lower:]')
if [[ "$UNAME" == *"darwin"* ]]; then
  BOOTSTRAP="$DIR/scripts/bin/bootstrap-macos"
else
  BOOTSTRAP="$DIR/scripts/bin/bootstrap-linux"
fi

chmod +x "$BOOTSTRAP"
cd "$DIR" && "$BOOTSTRAP"
