#!/usr/bin/env bash
# Friend install for macOS.
# Run with:  /bin/bash -c "$(curl -fsSL https://ecodia.au/friend/install/install.sh)"
# A piped script carries no quarantine attribute, so macOS does not block it.
# No Homebrew, no admin password: VS Code comes straight from Microsoft's
# notarized download, git comes from Apple's Command Line Tools.
#
# shell-lint-ok: no Homebrew prefix is referenced anywhere in this script; the
# VS Code install is a direct Microsoft download unzipped into /Applications
# (falling back to ~/Applications), and git is the system/CLT git resolved via
# PATH. Nothing is hardcoded to /opt/homebrew or /usr/local.

set -e

# The on-disk folder keeps its original name so existing installs update in place.
INSTALL_DIR="$HOME/Familiar"
REPO_URL="https://github.com/EcodiaCode/friend-starter.git"
VSCODE_URL="https://update.code.visualstudio.com/latest/darwin-universal/stable"

echo ""
echo "==========================================="
echo "  Friend install"
echo "  ecodia.au/friend"
echo "==========================================="
echo ""

# Step 1: Command Line Tools (provides git + a real python3). Check
# xcode-select -p, NOT "command -v git": on a stock Mac /usr/bin/git is a shim
# that exists but only triggers the CLT install when run, so command -v would
# wrongly report git present and we would hit the install prompt mid-clone.
echo "Step 1 of 3: checking for developer tools ..."
if ! xcode-select -p >/dev/null 2>&1; then
  echo "  Not installed. A grey Apple window will open to install the Command Line Tools."
  echo "  Click Install in it, agree, and wait for it to finish (it can take 10 minutes)."
  xcode-select --install || true
  tries=0
  until xcode-select -p >/dev/null 2>&1; do
    sleep 10
    tries=$((tries+1))
    echo "  ... still waiting for the Command Line Tools to finish ..."
    if [ "$tries" -ge 90 ]; then
      echo ""
      echo "  The developer tools did not finish in time. Please run this again and let"
      echo "  the grey Apple window fully finish, or email code@ecodia.au and we will help."
      exit 1
    fi
  done
fi
echo "  developer tools ok."
echo ""

# Step 2: Visual Studio Code, straight from Microsoft (signed + notarized).
echo "Step 2 of 3: checking for Visual Studio Code ..."
if [ ! -d "/Applications/Visual Studio Code.app" ] && [ ! -d "$HOME/Applications/Visual Studio Code.app" ]; then
  echo "  Visual Studio Code is missing. Downloading it from Microsoft ..."
  TMP_ZIP="$(mktemp -d)/vscode.zip"
  curl -fsSL "$VSCODE_URL" -o "$TMP_ZIP"
  echo "  Unpacking ..."
  TMP_EXTRACT="$(mktemp -d)"
  ditto -x -k "$TMP_ZIP" "$TMP_EXTRACT"
  if [ -w "/Applications" ]; then
    rm -rf "/Applications/Visual Studio Code.app"
    mv "$TMP_EXTRACT/Visual Studio Code.app" "/Applications/"
    VSCODE_APP="/Applications/Visual Studio Code.app"
  else
    mkdir -p "$HOME/Applications"
    rm -rf "$HOME/Applications/Visual Studio Code.app"
    mv "$TMP_EXTRACT/Visual Studio Code.app" "$HOME/Applications/"
    VSCODE_APP="$HOME/Applications/Visual Studio Code.app"
  fi
  rm -rf "$TMP_ZIP" "$TMP_EXTRACT"
else
  if [ -d "/Applications/Visual Studio Code.app" ]; then VSCODE_APP="/Applications/Visual Studio Code.app"; else VSCODE_APP="$HOME/Applications/Visual Studio Code.app"; fi
fi
echo "  Visual Studio Code ok."
echo ""

# Step 3: the Friend pack.
echo "Step 3 of 3: setting up your Friend in $INSTALL_DIR ..."
if [ -d "$INSTALL_DIR/.git" ]; then
  echo "  Existing install detected. Pulling the latest updates ..."
  ( cd "$INSTALL_DIR" && git pull --ff-only ) || echo "  (pull skipped, local changes present)"
else
  if [ -d "$INSTALL_DIR" ]; then
    BACKUP="$INSTALL_DIR.bak-$(date +%Y%m%d-%H%M%S)"
    echo "  Existing folder detected. Backing it up to $BACKUP."
    mv "$INSTALL_DIR" "$BACKUP"
  fi
  git clone "$REPO_URL" "$INSTALL_DIR"
fi
echo "  pack ok."
echo ""

# Install the Claude Code extension via the VS Code CLI (best effort).
CODE_BIN="$VSCODE_APP/Contents/Resources/app/bin/code"
if [ -x "$CODE_BIN" ]; then
  echo "Installing the Claude extension ..."
  "$CODE_BIN" --install-extension anthropic.claude-code --force >/dev/null 2>&1 || echo "  (extension step skipped; you can add it from the Extensions panel)"
fi

# Pre-trust the install folder so VS Code never shows the "trust this folder?"
# prompt (clicking No would silently disable the hooks). Best effort.
python3 -c "import json,os; p=os.path.expanduser('~/Library/Application Support/Code/User/settings.json'); os.makedirs(os.path.dirname(p),exist_ok=True); d=(json.load(open(p)) if os.path.exists(p) else {}); d['security.workspace.trust.enabled']=False; json.dump(d,open(p,'w'),indent=2)" >/dev/null 2>&1 || true

echo "Opening Visual Studio Code at $INSTALL_DIR ..."
open -a "$VSCODE_APP" "$INSTALL_DIR" || open "$INSTALL_DIR"

echo ""
echo "==========================================="
echo "  Done. Visual Studio Code is open at your Friend folder ($INSTALL_DIR)."
echo ""
echo "  Last steps, inside VS Code:"
echo "    1. If the Claude panel is not already there, open the Extensions"
echo "       panel (four-squares icon, left side), search Claude, install it."
echo "    2. Sign in to your AI provider when it asks."
echo "    3. Open the Claude chat and say hello to your Friend."
echo ""
echo "  Any question, reply on your welcome email."
echo "==========================================="
