#!/usr/bin/env bash
#
# VS Code extension installer for macOS and Linux (Ubuntu).
#
# Usage:
#   ./install.sh                          # install into the default profile
#   ./install.sh --profile "MyProfile"    # install into a named profile
#   ./install.sh --help
#
# If --profile is provided and the profile does not exist, VS Code creates
# it automatically. Quote names that contain spaces.

set -euo pipefail
IFS=$'\n\t'

readonly EXTENSIONS=(
  "docker.docker"
  "github.copilot-chat"
  "github.github-vscode-theme"
  "ms-vscode-remote.vscode-remote-extensionpack"
  "pkief.material-icon-theme"
)

PROFILE=""

usage() {
  cat <<EOF
Usage: $(basename "$0") [--profile "ProfileName"]

Installs a curated list of VS Code extensions on macOS or Linux.

Options:
  -p, --profile <name>   Install into the named VS Code profile.
                         VS Code creates the profile if it doesn't exist.
  -h, --help             Show this help and exit.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -p|--profile)
      if [[ $# -lt 2 || -z "${2:-}" ]]; then
        echo "Error: --profile requires a non-empty value." >&2
        exit 2
      fi
      PROFILE="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Error: unknown argument '$1'." >&2
      usage >&2
      exit 2
      ;;
  esac
done

OS="$(uname -s)"
case "$OS" in
  Darwin|Linux) ;;
  *)
    echo "Error: unsupported OS '$OS'. Use install.ps1 on Windows." >&2
    exit 1
    ;;
esac

if ! command -v code >/dev/null 2>&1; then
  cat >&2 <<'EOF'
Error: the 'code' command is not on your PATH.

  macOS:  open VS Code, press Cmd+Shift+P, run
          "Shell Command: Install 'code' command in PATH".
  Linux:  install VS Code from https://code.visualstudio.com/
          (or: sudo snap install --classic code), then reopen your shell.
EOF
  exit 1
fi

declare -a CODE_ARGS=()
if [[ -n "$PROFILE" ]]; then
  CODE_ARGS+=("--profile" "$PROFILE")
fi

LOG_FILE="$(mktemp -t vscode-install.XXXXXX)"
trap 'rm -f "$LOG_FILE"' EXIT

header="Installing ${#EXTENSIONS[@]} extension(s)"
[[ -n "$PROFILE" ]] && header+=" into profile '$PROFILE'"
echo "$header..."
echo

installed=0
failed=0
declare -a FAILED_LIST=()

for ext in "${EXTENSIONS[@]}"; do
  printf '  -> %-55s ' "$ext"
  if code "${CODE_ARGS[@]}" --install-extension "$ext" --force >"$LOG_FILE" 2>&1; then
    echo "ok"
    installed=$((installed + 1))
  else
    echo "FAILED"
    failed=$((failed + 1))
    FAILED_LIST+=("$ext")
    sed 's/^/       /' "$LOG_FILE" >&2 || true
  fi
done

echo
echo "Done. Installed: ${installed}, Failed: ${failed}"

if (( failed > 0 )); then
  echo "Failed extensions:" >&2
  for f in "${FAILED_LIST[@]}"; do
    echo "  - $f" >&2
  done
  exit 1
fi
