Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/igalklebanov/.dotfiles.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944#!/usr/bin/env bash
# lifted from Dillon Mulroy the great.
set -euo pipefail
# Colors for outputreadonly RED='\033[0;31m'readonly GREEN='\033[0;32m'readonly YELLOW='\033[0;33m'readonly BLUE='\033[0;34m'readonly CYAN='\033[0;36m'readonly RESET='\033[0m'readonly BOLD='\033[1m'
# Script metadatareadonly SCRIPT_NAME="dot"readonly VERSION="1.0.0"DOTFILES_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"readonly DOTFILES_DIR
# Configurationreadonly PACKAGES_DIR="${DOTFILES_DIR}/homebrew"readonly HOME_DIR="${DOTFILES_DIR}/home"readonly GITHUB_EMAIL="igalklebanov@gmail.com"readonly GITHUB_KEY_PATH="${HOME}/.ssh/id_ed25519_github"
# Progress indicatorsCURRENT_STEP=0TOTAL_STEPS=0
# Helper functions
print_header() { echo -e "\n${BOLD}${BLUE}==>${RESET} ${BOLD}$1${RESET}"}
print_success() { echo -e "${GREEN}✓${RESET} $1"}
print_error() { echo -e "${RED}✗${RESET} $1" >&2}
print_warning() { echo -e "${YELLOW}⚠${RESET} $1"}
print_info() { echo -e "${CYAN}ℹ${RESET} $1"}
print_step() { ((CURRENT_STEP++)) echo -e "\n${BOLD}[${CURRENT_STEP}/${TOTAL_STEPS}]${RESET} $1"}
command_exists() { command -v "$1" >/dev/null 2>&1}
confirm() { local prompt="${1:-Continue?}" local default="${2:-n}" if [[ "$default" == "y" ]]; then prompt="$prompt [Y/n]: " else prompt="$prompt [y/N]: " fi
echo -ne "\n${prompt}: " read -r response case "$response" in [yY][eE][sS]|[yY]) return 0 ;; [nN][oO]|[nN]) return 1 ;; "") if [[ "$default" == "y" ]]; then return 0 else return 1 fi ;; *) return 1 ;; esac}
check_dependencies() { local deps=("$@") local missing=() for dep in "${deps[@]}"; do if ! command_exists "$dep"; then missing+=("$dep") fi done if [[ ${#missing[@]} -gt 0 ]]; then print_error "Missing dependencies: ${missing[*]}" return 1 fi return 0}
# Installation functions
install_homebrew() { print_step "Installing Homebrew" if command_exists brew; then print_success "Homebrew is already installed" return 0 fi print_info "Homebrew is not installed. Installing now..." # Create temporary log file for installation output local log_file log_file=$(mktemp) local exit_code=0 print_info "Running Homebrew installer (non-interactive mode)..." # Run installer with non-interactive flag and capture output if NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" > "$log_file" 2>&1; then print_success "Homebrew installation successful" print_info "Configuring Homebrew environment..."
eval "$(/opt/homebrew/bin/brew shellenv)"
print_success "Homebrew environment configured" else exit_code=$? print_error "Homebrew installation failed (exit code: $exit_code)" print_info "Installation output:" if [[ -s "$log_file" ]]; then # Show last 20 lines of output for context tail -20 "$log_file" | while IFS= read -r line; do echo " $line" done else print_warning "No installation output captured" fi print_info "Troubleshooting:" print_info " - Check if you have sufficient disk space" print_info " - Ensure you have admin privileges" print_info " - Check network connectivity" print_info " - Try running manually: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"" rm "$log_file" return 1 fi # Cleanup log file rm "$log_file"}
use_brewfiles() { print_step "Installing packages from Brewfile" if [[ ! -f "${PACKAGES_DIR}/Brewfile" ]]; then print_error "Brewfile not found at ${PACKAGES_DIR}/Brewfile" return 1 fi print_info "Installing packages..." # Try to install all packages at once first if HOMEBREW_NO_AUTO_UPDATE=1 brew bundle --file="${PACKAGES_DIR}/Brewfile" --verbose; then print_success "All packages installed successfully" else print_warning "Some packages failed to install, trying individually..." # Parse Brewfile and try to install packages one by one local failed_packages=() local installed_count=0 while IFS= read -r line; do # Skip comments and empty lines [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line// }" ]] && continue # Extract package type and name if [[ "$line" =~ ^brew[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" print_info "Installing brew package: $package" if brew install "$package" 2>/dev/null; then ((++installed_count)) else print_warning "Failed to install: $package" failed_packages+=("brew:$package") fi elif [[ "$line" =~ ^cask[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" print_info "Installing cask: $package" if brew install --cask "$package" 2>/dev/null; then ((++installed_count)) else print_warning "Failed to install: $package" failed_packages+=("cask:$package") fi fi done < "${PACKAGES_DIR}/Brewfile" if [[ ${#failed_packages[@]} -gt 0 ]]; then print_warning "Failed to install ${#failed_packages[@]} packages:" printf " - %s\n" "${failed_packages[@]}" # Save failed packages to a file for reference local failed_file failed_file="${PACKAGES_DIR}/failed_packages_$(date +%Y%m%d_%H%M%S).txt" printf "%s\n" "${failed_packages[@]}" > "$failed_file" print_info "Failed packages saved to: $failed_file" fi print_success "Successfully installed $installed_count packages" fi
# Automatically discover and ask about contexts (bundle.*) # This finds Brewfile.aws, Brewfile.work, etc. for brewfile in "${PACKAGES_DIR}"/Brewfile.*; do # Ensure it's a file and not the base 'bundle' [[ -f "$brewfile" ]] || continue local filename=$(basename "$brewfile") local context="${filename#Brewfile.}" if confirm "Install ${BOLD}${context}${RESET} specific packages?" "n"; then print_info "Installing $context packages..." # Use the robust bundle + fallback logic if ! HOMEBREW_NO_AUTO_UPDATE=1 brew bundle --file="$brewfile" --verbose; then print_warning "Bundle for $context failed, trying individual install..." # Dillon's manual fallback loop while IFS= read -r line; do [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line// }" ]] && continue # Extract package type and name if [[ "$line" =~ ^brew[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" print_info "Installing brew package: $package" if brew install "$package" 2>/dev/null; then ((++installed_count)) else print_warning "Failed to install: $package" failed_packages+=("brew:$package") fi elif [[ "$line" =~ ^cask[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" print_info "Installing cask: $package" if brew install --cask "$package" 2>/dev/null; then ((++installed_count)) else print_warning "Failed to install: $package" failed_packages+=("cask:$package") fi fi done < "$brewfile"
if [[ ${#failed_packages[@]} -gt 0 ]]; then print_warning "Failed to install ${#failed_packages[@]} packages:" printf " - %s\n" "${failed_packages[@]}" # Save failed packages to a file for reference local failed_file failed_file="${PACKAGES_DIR}/failed_packages_$(date +%Y%m%d_%H%M%S).txt" printf "%s\n" "${failed_packages[@]}" > "$failed_file" print_info "Failed packages saved to: $failed_file" fi print_success "Successfully installed $installed_count packages" fi # Install AWS CLI from official web installer (not brew) if [[ "$context" == "aws" ]]; then print_info "Installing AWS CLI from official installer..." local aws_cli_pkg aws_cli_pkg=$(mktemp /tmp/AWSCLIV2.XXXXXX.pkg) if curl -sSL "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "$aws_cli_pkg"; then sudo installer -pkg "$aws_cli_pkg" -target / rm -f "$aws_cli_pkg" print_success "AWS CLI installed from official installer" else print_warning "Failed to download AWS CLI installer" rm -f "$aws_cli_pkg" fi fi else print_info "Skipping $context." fi done}
stow_dotfiles() { print_step "Stowing configuration files" if ! command_exists stow; then print_error "GNU Stow is not installed" print_info "Please install stow via Homebrew: brew install stow" return 1 fi print_info "Stowing files from ${HOME_DIR} to ${HOME}..." # Create backup directory for existing configs local backup_dir backup_dir="${DOTFILES_DIR}/backups/$(date +%Y%m%d_%H%M%S)" local files_to_backup=() # Check for existing files that would be overwritten while IFS= read -r -d '' file; do local relative_path="${file#"${HOME_DIR}"/}" local target_path="${HOME}/${relative_path}" if [[ -e "$target_path" && ! -L "$target_path" ]]; then files_to_backup+=("$relative_path") fi done < <(find "${HOME_DIR}" -type f -print0) if [[ ${#files_to_backup[@]} -gt 0 ]]; then print_warning "The following paths will be replaced:" local display_files=() for f in "${files_to_backup[@]}"; do if [[ "$f" == ".config/"*/* ]]; then local subdir="${f#*/}" display_files+=(".config/${subdir%%/*}/*") else display_files+=("$f") fi done printf " %s\n" "${display_files[@]}" | sort -u if confirm "Create backups of existing files?" "y"; then mkdir -p "$backup_dir" for file in "${files_to_backup[@]}"; do local src="${HOME}/${file}" local dst="${backup_dir}/${file}" mkdir -p "$(dirname "$dst")" if ! cp -p "$src" "$dst"; then print_error "Failed to backup: $src" return 1 fi done print_success "Backups created in ${backup_dir}" fi fi if stow -R -v -d "${DOTFILES_DIR}" -t "${HOME}" home; then print_success "Dotfiles stowed successfully" else print_error "Failed to stow dotfiles" return 1 fi}
setup_raycast() { if [[ ! -d "/Applications/Raycast.app" ]]; then print_info "Raycast not installed, skipping setup" return 0 fi
print_step "Setting up Raycast"
local onboarding_completed onboarding_completed=$(defaults read com.raycast.macos onboardingCompleted 2>/dev/null)
if [[ "$onboarding_completed" != "1" ]]; then open -a "Raycast" fi
local spotlight_status spotlight_status=$(/usr/libexec/PlistBuddy -c "Print :AppleSymbolicHotKeys:64:enabled" ~/Library/Preferences/com.apple.symbolichotkeys.plist 2>/dev/null)
if [[ "$spotlight_status" == "false" ]]; then print_success "Spotlight shortcut is already disabled." else print_warning "macOS Spotlight shortcut is still enabled." print_info "Opening Keyboard Shortcuts — please uncheck 'Show Spotlight search'." open "x-apple.systempreferences:com.apple.Keyboard-Settings.extension?Spotlight" fi}
# Helper to determine OpenCode installation methodget_opencode_install_method() { local opencode_path opencode_path=$(command -v opencode 2>/dev/null) || { echo "not_installed"; return; } case "$opencode_path" in "${HOME}/.opencode"*) echo "native" ;; "/opt/homebrew"*|"/usr/local/Cellar"*) echo "brew" ;; *) echo "unknown" ;; esac}
# Helper to check for multiple OpenCode installationscheck_opencode_conflicts() { local found_paths=() local install_method # Check native installation if [[ -x "${HOME}/.opencode/bin/opencode" ]]; then found_paths+=("${HOME}/.opencode/bin/opencode (native)") fi # Check homebrew installation if command -v brew >/dev/null 2>&1; then local brew_path brew_path=$(brew --prefix 2>/dev/null)/bin/opencode if [[ -x "$brew_path" ]]; then found_paths+=("$brew_path (brew)") fi fi
install_method=$(get_opencode_install_method)
if [[ $install_method == "unknown" ]]; then found_paths+=("unknown") fi if [[ ${#found_paths[@]} -gt 1 ]]; then echo "${found_paths[*]}" return 0 fi
return 1}
install_opencode() { print_step "Installing OpenCode CLI" # Save current shell options for restoration local _saved_opts="$-" # Check current installation status local install_method install_method=$(get_opencode_install_method) case "$install_method" in native) print_success "OpenCode is already installed via native installer (recommended)" return 0 ;; brew) print_warning "OpenCode is installed via Homebrew" print_info "Native installer is recommended for faster updates" if confirm "Migrate to native installer?" "y"; then print_info "Migrating OpenCode to native installer..." # Temporarily disable exit on error set +e # Remove old installation print_info "Removing Homebrew installation..." brew uninstall opencode 2>/dev/null # Install via native installer print_info "Installing via native installer..." if curl -fsSL https://opencode.ai/install | bash; then print_success "OpenCode migrated to native installer successfully" print_info "You may need to restart your shell" set -"$_saved_opts" 2>/dev/null || true return 0 else print_error "Installation failed, reinstalling via Homebrew..." brew install opencode set -"$_saved_opts" 2>/dev/null || true return 1 fi else print_info "Keeping existing Homebrew installation" return 0 fi ;; unknown) print_success "OpenCode is already installed" return 0 ;; esac # Fresh installation - use native installer (fastest updates) print_info "Installing OpenCode CLI..." # Temporarily disable exit on error for installation attempts set +e # Try native installer first (recommended - gets updates faster than brew) print_info "Running native installer..." if curl -fsSL https://opencode.ai/install | bash; then print_success "OpenCode installed successfully via native installer" print_info "You may need to restart your shell or add ~/.opencode/bin to your PATH" set -"$_saved_opts" 2>/dev/null || true return 0 else print_warning "Native installer failed, trying Homebrew..." fi # Fallback to Homebrew if command_exists brew; then print_info "Installing via Homebrew..." if brew install opencode; then print_success "OpenCode installed successfully via Homebrew" set -"$_saved_opts" 2>/dev/null || true return 0 else print_warning "Homebrew installation failed, trying bun..." fi fi
print_error "All installation methods failed" print_info "Try manually: curl -fsSL https://opencode.ai/install | bash" set -"$_saved_opts" 2>/dev/null || true return 1}
install_socket_firewall() { print_step "Installing Socket Firewall Free" local bin_dir="${HOME}/.local/bin" local sfw_path="${bin_dir}/sfw" local download_url="https://github.com/SocketDev/sfw-free/releases/latest/download/sfw-free-macos-arm64" mkdir -p "$bin_dir" print_info "Downloading Socket Firewall Free..." if curl -fsSL -o "$sfw_path" "$download_url"; then print_success "Downloaded successfully" else print_error "Failed to download Socket Firewall Free" return 1 fi print_info "Removing quarantine attribute..." if xattr -dr com.apple.quarantine "$sfw_path" 2>/dev/null; then print_success "Quarantine removed" else print_warning "Could not remove quarantine (may not be needed)" fi # Make executable chmod +x "$sfw_path" if "$sfw_path" --help >/dev/null 2>&1; then print_success "Socket Firewall Free installed successfully" return 0 else print_error "Installation verification failed" return 1 fi}
ensure_ssh_config_keychain() { local key_path="$1" local ssh_config="${HOME}/.ssh/config" # Ensure config exists with correct permissions mkdir -p "${HOME}/.ssh" chmod 700 "${HOME}/.ssh" touch "$ssh_config" chmod 600 "$ssh_config" # Check if keychain config already present if grep -q "UseKeychain yes" "$ssh_config" 2>/dev/null; then return 0 fi print_info "Configuring SSH for keychain integration..." # Find insertion point after Include directives if grep -q "^Include " "$ssh_config"; then # Insert after last Include line using sed local tmp_file="${ssh_config}.tmp" sed '/^Include /a\\Host *\ UseKeychain yes\ AddKeysToAgent yes\ IdentityFile '"$key_path"'' "$ssh_config" > "$tmp_file" mv "$tmp_file" "$ssh_config" chmod 600 "$ssh_config" else # No Include lines, prepend to file local tmp_file="${ssh_config}.tmp" { echo "" echo "Host *" echo " UseKeychain yes" echo " AddKeysToAgent yes" echo " IdentityFile $key_path" echo "" cat "$ssh_config" } > "$tmp_file" mv "$tmp_file" "$ssh_config" chmod 600 "$ssh_config" fi print_success "SSH config updated for keychain integration"}
ensure_known_hosts() { local host="$1" local known_hosts="${HOME}/.ssh/known_hosts" if [[ -z "$host" ]]; then print_error "ensure_known_hosts: host parameter required" return 1 fi # Escape dots for grep pattern local host_pattern="${host//./\\.}" # Check if host already in known_hosts (idempotent) if [[ -f "$known_hosts" ]] && grep -q "^${host_pattern} " "$known_hosts"; then return 0 fi print_info "Adding ${host} to known hosts..." # Ensure .ssh directory exists with correct permissions mkdir -p "${HOME}/.ssh" chmod 700 "${HOME}/.ssh" # Fetch host's ed25519 key if ssh-keyscan -t ed25519 "$host" >> "$known_hosts" 2>/dev/null; then chmod 600 "$known_hosts" print_success "${host} host key added" else print_warning "Failed to fetch ${host} host key (check network connection)" print_info "You can add it later with: ssh-keyscan -t ed25519 ${host} >> ~/.ssh/known_hosts" fi}
generate_ssh_key() { print_step "Generating SSH key for GitHub" if [[ ! -f "$GITHUB_KEY_PATH" ]]; then print_info "Generating new SSH key..." mkdir -p "${HOME}/.ssh" chmod 700 "${HOME}/.ssh" if ! ssh-keygen -t ed25519 -C "$GITHUB_EMAIL" -f "$GITHUB_KEY_PATH"; then print_error "Failed to generate SSH key" return 1 fi print_success "SSH key generated successfully" else print_success "SSH key already exists at $GITHUB_KEY_PATH" fi ensure_ssh_config_keychain "$GITHUB_KEY_PATH" ensure_known_hosts "github.com" print_info "Adding key to ssh-agent and macOS Keychain..." if ssh-add --apple-use-keychain "$GITHUB_KEY_PATH" 2>/dev/null; then print_success "Key added to ssh-agent and macOS Keychain" else print_warning "Failed to add key to ssh-agent (you may need to add manually)" fi if command_exists pbcopy; then pbcopy < "${GITHUB_KEY_PATH}.pub" print_success "Public key copied to clipboard!" fi print_info "Add the public key to GitHub:" echo " GitHub > Settings > SSH and GPG keys > New SSH key"}
cmd_gen_ssh_key() { print_header "Generating SSH key for GitHub"
# Parse options local email=""
while [[ $# -gt 0 ]]; do case "$1" in -h|--help) cat << EOF${BOLD}USAGE:${RESET} ${SCRIPT_NAME} gen-ssh-key [EMAIL]
${BOLD}DESCRIPTION:${RESET} Generate a new SSH key for GitHub, GitLab, or other Git services. The key will be automatically added to ssh-agent and the public key will be copied to your clipboard for easy pasting.
${BOLD}ARGUMENTS:${RESET} EMAIL Email address to associate with the SSH key (optional) If not provided, you will be prompted for it
${BOLD}EXAMPLES:${RESET} ${SCRIPT_NAME} gen-ssh-key # Prompts for email ${SCRIPT_NAME} gen-ssh-key user@github.com # Uses provided email
${BOLD}NOTES:${RESET} - Key name is derived from email domain (e.g., user@github.com → id_ed25519_github) - Keys are stored in ~/.ssh/ - Public key is automatically copied to clipboard - Key is automatically added to ssh-agent - If a key already exists, you will be prompted to overwrite
EOF return 0 ;; *) email="$1" shift ;; esac done
# Get email if not provided if [[ -z "$email" ]]; then read -r -p "Enter email address for SSH key: " email if [[ -z "$email" ]]; then print_error "Email is required" return 1 fi fi
# Validate email format (basic check) if [[ ! "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then print_error "Invalid email format: $email" return 1 fi
# Extract domain from email for key naming local domain domain=$(echo "$email" | sed 's/.*@//' | sed 's/\..*//') if [[ -z "$domain" ]]; then domain="key" fi
# Sanitize domain name (remove special characters) domain=$(echo "$domain" | tr -cd '[:alnum:]_-' | tr '[:upper:]' '[:lower:]')
# Set key path local key_name="id_ed25519_${domain}" local key_path="${HOME}/.ssh/${key_name}"
print_info "Key will be created at: $key_path"
# Check if key already exists if [[ -f "$key_path" ]]; then print_warning "SSH key already exists at $key_path" if ! confirm "Overwrite existing key?" "n"; then print_info "Key generation cancelled" return 0 fi
# Backup existing key local backup_path backup_path="${key_path}.backup.$(date +%Y%m%d_%H%M%S)" print_info "Backing up existing key to $(basename "$backup_path")" cp "$key_path" "$backup_path" cp "${key_path}.pub" "${backup_path}.pub" 2>/dev/null || true fi
# Ensure .ssh directory exists with correct permissions mkdir -p "${HOME}/.ssh" chmod 700 "${HOME}/.ssh"
# Generate SSH key print_info "Generating SSH key..." if ssh-keygen -t ed25519 -C "$email" -f "$key_path" -N ""; then print_success "SSH key generated successfully" else print_error "Failed to generate SSH key" return 1 fi
# Add key to ssh-agent print_info "Adding key to ssh-agent..."
# Start ssh-agent if not running if ! pgrep -u "$USER" ssh-agent > /dev/null 2>&1; then print_info "Starting ssh-agent..." eval "$(ssh-agent -s)" > /dev/null fi
if ssh-add "$key_path" 2>/dev/null; then print_success "Key added to ssh-agent" else print_warning "Failed to add key to ssh-agent (you may need to start ssh-agent)" fi
# Copy public key to clipboard if command_exists pbcopy; then pbcopy < "${key_path}.pub" print_success "Public key copied to clipboard!" else print_warning "pbcopy not available, skipping clipboard copy" fi
# Display instructions echo "" print_info "Next steps:" echo " 1. The public key has been copied to your clipboard" echo " 2. Go to your Git service (GitHub, GitLab, etc.):" echo " - GitHub: Settings > SSH and GPG keys > New SSH key" echo " - GitLab: Preferences > SSH Keys" echo " 3. Paste the key and save" echo "" print_info "Key details:" echo " Private key: $key_path" echo " Public key: ${key_path}.pub" echo " Email: $email" echo ""
# Show public key print_info "Public key contents:" cat "${key_path}.pub" echo ""
print_success "SSH key generation complete!"}
# Command functions
install_vscode_extensions() { print_step "Installing VS Code extensions" if ! command_exists code; then print_warning "VS Code not installed, skipping extensions" return 0 fi local extensions_file="${DOTFILES_DIR}/vscode/extensions.json" if [[ ! -f "$extensions_file" ]]; then print_info "No extensions.json found, skipping" return 0 fi if ! command_exists jq; then print_warning "jq not installed, skipping VS Code extensions" print_info "Install jq to enable extension sync: brew install jq" return 0 fi print_info "Installing extensions from extensions.json..." local installed=0 local failed=0 while IFS= read -r extension; do print_info "Installing: $extension" if code --install-extension "$extension" --force 2>/dev/null; then ((++installed)) else print_warning "Failed to install: $extension" ((++failed)) fi done < <(jq -r '.[]' "$extensions_file") if [[ $installed -gt 0 ]]; then print_success "Installed $installed VS Code extensions" fi if [[ $failed -gt 0 ]]; then print_warning "$failed extensions failed to install" fi}
cmd_init() { print_header "Initializing dotfiles" TOTAL_STEPS=8 CURRENT_STEP=0 # Run all installation steps install_homebrew || return 1 use_brewfiles || return 1 stow_dotfiles || return 1 install_vscode_extensions || print_warning "VS Code extension install failed (continuing)" setup_raycast || print_warning "Setting up Raycast failed (continuing)" install_opencode || print_warning "OpenCode installation failed (continuing)" install_socket_firewall || print_warning "Socket Firewall Free installation failed (continuing)" if [[ "${SKIP_SSH:-}" != "true" ]]; then generate_ssh_key || print_warning "SSH key generation failed (continuing)" fi print_header "Initialization complete! 🎉"}
cmd_update() { print_header "Updating dotfiles" # Pull latest changes print_info "Pulling latest changes..." if git -C "$DOTFILES_DIR" pull; then print_success "Repository updated" else print_error "Failed to update repository" return 1 fi # Update packages if confirm "Update Homebrew packages?" "y"; then print_info "Updating Homebrew..." # WARP adds latency that triggers brew's curl speed-limit abort # Pre-download API files to work around this if pgrep -q "Cloudflare WARP"; then print_info "Cloudflare WARP detected, pre-downloading Homebrew API..." local api_cache="$HOME/Library/Caches/Homebrew/api" mkdir -p "$api_cache" curl -fsSL -o "$api_cache/formula.jws.json" "https://formulae.brew.sh/api/formula.jws.json" 2>/dev/null curl -fsSL -o "$api_cache/cask.jws.json" "https://formulae.brew.sh/api/cask.jws.json" 2>/dev/null fi brew update brew upgrade print_success "Packages updated" fi # Re-stow dotfiles if confirm "Re-stow dotfiles?" "y"; then stow_dotfiles fi}
cmd_doctor() { print_header "Running diagnostics" local issues=0 # Check Homebrew if command_exists brew; then print_success "Homebrew installed" else print_error "Homebrew not installed" ((++issues)) fi # Check Stow if command_exists stow; then print_success "GNU Stow installed" else print_error "GNU Stow not installed" ((++issues)) fi # Check OpenCode if command_exists opencode; then print_success "OpenCode installed" # Check installation method using helper function local install_method install_method=$(get_opencode_install_method) case "$install_method" in native) print_success "OpenCode installed via native installer (recommended)" ;; brew) print_warning "OpenCode installed via Homebrew" print_info "Native installer gets updates faster: curl -fsSL https://opencode.ai/install | bash" print_info "Or run 'dot init' to migrate automatically" ;; *) print_warning "OpenCode installed via unknown method" print_info "Consider reinstalling via: curl -fsSL https://opencode.ai/install | bash" ;; esac # Check for multiple installations (potential conflicts) local conflicts if conflicts=$(check_opencode_conflicts); then print_warning "Multiple OpenCode installations detected:" for path in $conflicts; do print_info " - $path" done print_info "This may cause version conflicts. Consider removing duplicate installations." fi # Check if we can get version (indicates it's working) if opencode --version >/dev/null 2>&1; then print_success "OpenCode is functional" else print_warning "OpenCode may need configuration" print_info "Run 'opencode' and use /connect to configure a provider" fi else print_warning "OpenCode not installed" print_info "Install with: curl -fsSL https://opencode.ai/install | bash" print_info "Or run 'dot init' to install automatically" fi # Check Socket Firewall Free if command_exists sfw; then print_success "Socket Firewall Free (sfw) installed" # Try to get version info if available local sfw_path sfw_path=$(command -v sfw) print_info "Location: $sfw_path" # Verify it's functional if sfw --help >/dev/null 2>&1; then print_success "Socket Firewall Free is functional" print_info "Usage: sfw npm install, sfw pip install, sfw cargo fetch" else print_warning "Socket Firewall Free may not be working correctly" fi else print_warning "Socket Firewall Free (sfw) not installed" print_info "Install with: 'dot init' or manually download from GitHub releases" print_info "Protects against malicious packages in real-time" fi # Check symlinks local broken_links=0 while IFS= read -r -d '' link; do if [[ ! -e "$link" ]]; then ((++broken_links)) fi done < <(find "${HOME}" -maxdepth 3 -type l -print0 2>/dev/null) if [[ $broken_links -eq 0 ]]; then print_success "No broken symlinks found" else print_warning "Found $broken_links broken symlinks" fi # Check SSH key if [[ -f "$GITHUB_KEY_PATH" ]]; then print_success "GitHub SSH key exists" else print_warning "GitHub SSH key not found" fi # Check key development tools local dev_tools=("git" "node" "npm") local missing_tools=() for tool in "${dev_tools[@]}"; do if command_exists "$tool"; then print_success "$tool is available" else missing_tools+=("$tool") fi done if [[ ${#missing_tools[@]} -gt 0 ]]; then print_warning "Missing development tools: ${missing_tools[*]}" fi # Check if dotfiles directory is in PATH if echo "$PATH" | grep -q "$DOTFILES_DIR"; then print_success "Dotfiles directory is in PATH" else print_warning "Dotfiles directory not in PATH - 'dot' command may not work globally" print_info "Add 'export PATH=\"$DOTFILES_DIR:\$PATH\"' to your shell profile" fi if [[ $issues -eq 0 ]]; then print_header "All critical checks passed! ✨" if [[ ${#missing_tools[@]} -gt 0 ]]; then print_info "Note: Some optional tools are missing but core functionality is intact" fi else print_header "Found $issues critical issues" fi}
cmd_link() { print_header "Creating symlink for dot command" local target_dir="/usr/local/bin" local link_path="${target_dir}/dot" # Check if we can write to target directory if [[ ! -w "$target_dir" ]]; then print_info "Need sudo access to create symlink in ${target_dir}" target_dir="${HOME}/.local/bin" link_path="${target_dir}/dot" mkdir -p "$target_dir" print_info "Using ${target_dir} instead" fi # Remove existing link if present if [[ -L "$link_path" ]]; then rm "$link_path" fi # Create symlink if ln -s "${DOTFILES_DIR}/dot" "$link_path"; then print_success "Created symlink at ${link_path}" print_info "Make sure ${target_dir} is in your PATH" else print_error "Failed to create symlink" return 1 fi}
cmd_unlink() { print_header "Removing dot symlink" local paths=( "/usr/local/bin/dot" "${HOME}/.local/bin/dot" "/usr/local/bin/dotfiles" # Legacy name "${HOME}/.local/bin/dotfiles" # Legacy name ) local found=false for link_path in "${paths[@]}"; do if [[ -L "$link_path" ]]; then if rm "$link_path"; then print_success "Removed symlink at ${link_path}" found=true else print_error "Failed to remove symlink at ${link_path}" fi fi done if [[ "$found" == false ]]; then print_warning "No dot symlink found" fi}
cmd_stow() { print_header "Stowing dotfiles" if ! command_exists stow; then print_error "GNU Stow is not installed" print_info "Install it first: brew install stow" return 1 fi print_info "Creating symlinks for dotfiles..." if stow -R -v -d "${DOTFILES_DIR}" -t "${HOME}" home; then print_success "Dotfiles stowed successfully" print_info "Configuration files are now symlinked to your home directory" else print_error "Failed to stow dotfiles" print_info "Check for conflicting files in your home directory" return 1 fi}
cmd_edit() { print_header "Opening dotfiles in editor" exec code "$DOTFILES_DIR"}
cmd_vscode_sync() { print_header "Syncing VS Code extensions" if ! command_exists code; then print_error "VS Code not installed" return 1 fi local extensions_file="${DOTFILES_DIR}/vscode/extensions.json" print_info "Fetching installed extensions..." local extensions extensions=$(code --list-extensions 2>/dev/null | sort) if [[ -z "$extensions" ]]; then print_warning "No extensions installed" return 0 fi local count count=$(echo "$extensions" | wc -l | tr -d ' ') print_info "Found $count extensions" # Create JSON array mkdir -p "$(dirname "$extensions_file")" echo "$extensions" | jq -R . | jq -s . > "$extensions_file" print_success "Synced $count extensions to vscode/extensions.json" print_info "Commit these changes to track extensions across machines"}
cmd_retry_failed() { print_header "Retrying failed package installations" # Find the most recent failed packages file local failed_file failed_file=$(find "${PACKAGES_DIR}" -name "failed_packages_*.txt" -type f 2>/dev/null | sort -r | head -1) if [[ -z "$failed_file" || ! -f "$failed_file" ]]; then print_info "No failed packages file found" return 0 fi print_info "Found failed packages file: $failed_file" print_info "Attempting to retry installation..." local retry_count=0 local success_count=0 while IFS= read -r package_info; do ((++retry_count)) if [[ "$package_info" =~ ^brew:(.+)$ ]]; then local package="${BASH_REMATCH[1]}" print_info "Retrying brew package: $package" if brew install "$package" 2>/dev/null; then print_success "Successfully installed: $package" ((++success_count)) else print_warning "Still failing: $package" fi elif [[ "$package_info" =~ ^cask:(.+)$ ]]; then local package="${BASH_REMATCH[1]}" print_info "Retrying cask: $package" if brew install --cask "$package" 2>/dev/null; then print_success "Successfully installed: $package" ((++success_count)) else print_warning "Still failing: $package" fi fi done < "$failed_file" print_info "Retry complete: $success_count/$retry_count packages installed" if [[ $success_count -eq $retry_count ]]; then print_success "All failed packages now installed!" rm "$failed_file" fi}
cmd_check_packages() { print_header "Checking installed packages" local missing_brew=() local missing_cask=() local installed_brew=() local installed_cask=() # Get lists of installed packages once to avoid repeated calls local installed_formulas local installed_casks installed_formulas=$(brew list --formula 2>/dev/null || true) installed_casks=$(brew list --cask 2>/dev/null || true) # Find all Brewfile* files and check each while IFS= read -r -d '' brewfile; do local filename=$(basename "$brewfile") local context if [[ "$filename" == "Brewfile" ]]; then context="base" else context="${filename#Brewfile.}" fi print_info "Checking ${context} packages..." while IFS= read -r line; do [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line// }" ]] && continue if [[ "$line" =~ ^brew[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" local label="$package" [[ "$context" != "base" ]] && label="$package ($context)" if echo "$installed_formulas" | grep -q "^${package}$"; then installed_brew+=("$label") else missing_brew+=("$label") fi elif [[ "$line" =~ ^cask[[:space:]]+\"([^\"]+)\" ]]; then local package="${BASH_REMATCH[1]}" local label="$package" [[ "$context" != "base" ]] && label="$package ($context)" if echo "$installed_casks" | grep -q "^${package}$"; then installed_cask+=("$label") else missing_cask+=("$label") fi fi done < "$brewfile" done < <(find "${PACKAGES_DIR}" -name "Brewfile*" -type f -print0 | sort -z) # Report results print_header "Package Status Report" echo -e "\n${BOLD}Installed Packages:${RESET}" print_success "Brew formulas: ${#installed_brew[@]}" print_success "Casks: ${#installed_cask[@]}" if [[ ${#missing_brew[@]} -gt 0 || ${#missing_cask[@]} -gt 0 ]]; then echo -e "\n${BOLD}Missing Packages:${RESET}" if [[ ${#missing_brew[@]} -gt 0 ]]; then print_warning "Missing brew formulas (${#missing_brew[@]}):" printf " - %s\n" "${missing_brew[@]}" fi if [[ ${#missing_cask[@]} -gt 0 ]]; then print_warning "Missing casks (${#missing_cask[@]}):" printf " - %s\n" "${missing_cask[@]}" fi echo "" print_info "Run '${SCRIPT_NAME} init' to install missing packages" else print_success "All packages are installed!" fi}
cmd_package() { local subcommand="${1:-list}" shift || true case "$subcommand" in add) cmd_package_add "$@" ;; remove) cmd_package_remove "$@" ;; update) cmd_package_update "$@" ;; list) cmd_package_list "$@" ;; -h|--help|help) cmd_package_help ;; *) print_error "Unknown package subcommand: $subcommand" print_info "Run '${SCRIPT_NAME} package help' for usage" return 1 ;; esac}
cmd_package_add() { local package_name="" local bundle_file="base" local force_cask=false while [[ $# -gt 0 ]]; do case "$1" in --cask) force_cask=true shift ;; *) if [[ -z "$package_name" ]]; then package_name="$1" elif [[ "$bundle_file" == "base" ]]; then bundle_file="$1" fi shift ;; esac done if [[ -z "$package_name" ]]; then print_error "Package name required" print_info "Usage: ${SCRIPT_NAME} package add <package> [context] [--cask]" print_info "Contexts: base, aws, ecmascript, k8s, terraform, work (default: base)" return 1 fi local target_bundle if [[ "$bundle_file" == "base" ]]; then target_bundle="${PACKAGES_DIR}/Brewfile" elif [[ -f "${PACKAGES_DIR}/Brewfile.${bundle_file}" ]]; then target_bundle="${PACKAGES_DIR}/Brewfile.${bundle_file}" else print_error "Unknown bundle: $bundle_file" print_info "Available: base, aws, ecmascript, k8s, terraform, work" return 1 fi local package_type if [[ "$force_cask" == true ]]; then package_type="cask" else print_info "Detecting package type..." if brew info --json=v2 --formula "$package_name" >/dev/null 2>&1; then package_type="brew" elif brew info --json=v2 --cask "$package_name" >/dev/null 2>&1; then package_type="cask" else print_error "Package '$package_name' not found" print_info "Use --cask if this is a cask, or check the package name" return 1 fi fi local package_line="${package_type} \"${package_name}\"" if grep -q "^${package_line}$" "$target_bundle" 2>/dev/null; then print_warning "Package '$package_name' already exists in $(basename "$target_bundle")" return 0 fi print_header "Adding $package_type package: $package_name" print_info "Installing package..." if [[ "$package_type" == "cask" ]]; then if brew install --cask "$package_name"; then print_success "Package installed successfully" else print_error "Failed to install package" return 1 fi else if brew install "$package_name"; then print_success "Package installed successfully" else print_error "Failed to install package" return 1 fi fi print_info "Adding to bundle file..." if [[ ! -f "$target_bundle" ]]; then print_warning "Bundle file doesn't exist, creating: $target_bundle" mkdir -p "$(dirname "$target_bundle")" touch "$target_bundle" fi local temp_file temp_file=$(mktemp) local inserted=false while IFS= read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ ^${package_type}[[:space:]]+\"([^\"]+)\" ]] && [[ "$inserted" == false ]]; then local existing_package="${BASH_REMATCH[1]}" if [[ "$package_name" < "$existing_package" ]]; then echo "$package_line" >> "$temp_file" inserted=true fi fi echo "$line" >> "$temp_file" done < "$target_bundle" if [[ "$inserted" == false ]]; then echo "$package_line" >> "$temp_file" fi mv "$temp_file" "$target_bundle" print_success "Added '$package_name' to $(basename "$target_bundle")" print_info "Package will be included in future installations"}
cmd_package_remove() { local package_name="$1" local bundle_file="${2:-auto}" # Escape regex metacharacters in package name local escaped_package # shellcheck disable=SC2016 # Single quotes intentional - \& is sed backreference escaped_package=$(printf '%s' "$package_name" | sed 's/[.[\*^$()+?{|\\]/\\&/g')
if [[ -z "$package_name" ]]; then print_error "Package name required" print_info "Usage: ${SCRIPT_NAME} package remove <package-name> [base|aws|ecmascript|k8s|terraform|work|auto]" return 1 fi print_header "Removing package: $package_name" # Determine which bundle files to check local bundle_files=() if [[ "$bundle_file" == "base" ]]; then bundle_files=("${PACKAGES_DIR}/Brewfile") elif [[ -f "${PACKAGES_DIR}/Brewfile.${bundle_file}" ]]; then bundle_files=("${PACKAGES_DIR}/Brewfile.${bundle_file}") else while IFS= read -r -d '' f; do bundle_files+=("$f") done < <(find "${PACKAGES_DIR}" -name "Brewfile*" -type f -print0 | sort -z) fi local found=false local package_type="" # Find and remove from bundle files for target_bundle in "${bundle_files[@]}"; do if [[ ! -f "$target_bundle" ]]; then continue fi # Check if package exists if grep -q "^\\(brew\\|cask\\)[[:space:]]*\"${escaped_package}\"" "$target_bundle"; then found=true
# Determine package type if grep -q "^brew[[:space:]]*\"${escaped_package}\"" "$target_bundle"; then package_type="formula" else package_type="cask" fi
# Remove from bundle file print_info "Removing from $(basename "$target_bundle")..." local temp_file temp_file=$(mktemp) grep -v "^\\(brew\\|cask\\)[[:space:]]*\"${escaped_package}\"" "$target_bundle" > "$temp_file" mv "$temp_file" "$target_bundle" print_success "Removed '$package_name' from $(basename "$target_bundle")" fi done if [[ "$found" == false ]]; then print_warning "Package '$package_name' not found in any bundle files" return 0 fi # Ask if user wants to uninstall the actual package if confirm "Uninstall '$package_name' from system?" "n"; then print_info "Uninstalling package..." if [[ "$package_type" == "cask" ]]; then if brew uninstall --cask "$package_name"; then print_success "Package uninstalled successfully" else print_warning "Failed to uninstall package (it may have dependencies)" fi else if brew uninstall "$package_name"; then print_success "Package uninstalled successfully" else print_warning "Failed to uninstall package (it may have dependencies)" fi fi else print_info "Package removed from bundle but left installed on system" fi}
cmd_package_update() { local package_name="${1:-}" print_header "Updating packages" # Specific package update if [[ -n "$package_name" ]]; then print_info "Updating specific package: $package_name" local is_formula=false local is_cask=false if brew list --formula | grep -q "^${package_name}$"; then is_formula=true elif brew list --cask | grep -q "^${package_name}$"; then is_cask=true else print_error "Package '$package_name' is not installed" return 1 fi if [[ "$is_formula" == true ]]; then print_info "Updating brew formula: $package_name" if brew upgrade "$package_name"; then print_success "Updated $package_name successfully" else print_warning "Failed to update $package_name (may already be latest version)" fi elif [[ "$is_cask" == true ]]; then print_info "Updating cask: $package_name" if brew upgrade --cask "$package_name"; then print_success "Updated $package_name successfully" else print_warning "Failed to update $package_name (may already be latest version or not upgradeable)" fi fi return 0 fi # Update all packages from Brewfiles print_info "Updating Homebrew..." if brew update; then print_success "Homebrew updated successfully" else print_error "Failed to update Homebrew" return 1 fi # Collect all packages from all Brewfiles local brew_packages=() local cask_packages=() while IFS= read -r -d '' brewfile; do while IFS= read -r line; do [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line// }" ]] && continue if [[ "$line" =~ ^brew[[:space:]]+\"([^\"]+)\" ]]; then brew_packages+=("${BASH_REMATCH[1]}") elif [[ "$line" =~ ^cask[[:space:]]+\"([^\"]+)\" ]]; then cask_packages+=("${BASH_REMATCH[1]}") fi done < "$brewfile" done < <(find "${PACKAGES_DIR}" -name "Brewfile*" -type f -print0 | sort -z) # Remove duplicates local unique_brew=() local unique_cask=() if [[ ${#brew_packages[@]} -gt 0 ]]; then IFS=' ' read -r -a unique_brew <<< "$(printf '%s\n' "${brew_packages[@]}" | sort -u | tr '\n' ' ')" fi if [[ ${#cask_packages[@]} -gt 0 ]]; then IFS=' ' read -r -a unique_cask <<< "$(printf '%s\n' "${cask_packages[@]}" | sort -u | tr '\n' ' ')" fi local installed_formulas local installed_casks installed_formulas=$(brew list --formula 2>/dev/null || true) installed_casks=$(brew list --cask 2>/dev/null || true) local updated_packages=() # Update brew formulas for package in "${unique_brew[@]}"; do if echo "$installed_formulas" | grep -q "^${package}$"; then print_info "Updating brew formula: $package" if brew upgrade "$package" 2>/dev/null; then updated_packages+=("$package (formula)") fi fi done # Update casks for package in "${unique_cask[@]}"; do if echo "$installed_casks" | grep -q "^${package}$"; then print_info "Updating cask: $package" if brew upgrade --cask "$package" 2>/dev/null; then updated_packages+=("$package (cask)") fi fi done # Report results if [[ ${#updated_packages[@]} -gt 0 ]]; then print_success "Updated ${#updated_packages[@]} packages:" printf " - %s\n" "${updated_packages[@]}" else print_info "All packages are already up to date" fi # Cleanup if confirm "Clean up old versions?" "y"; then print_info "Cleaning up old package versions..." brew cleanup print_success "Cleanup completed" fi}
cmd_package_list() { local bundle_file="${1:-}"
print_header "Listing packages"
local installed_formulas local installed_casks installed_formulas=$(brew list --formula 2>/dev/null || true) installed_casks=$(brew list --cask 2>/dev/null || true)
local bundle_files=()
if [[ -z "$bundle_file" ]]; then while IFS= read -r -d '' f; do bundle_files+=("$f") done < <(find "${PACKAGES_DIR}" -name "Brewfile*" -type f -print0 | sort -z) elif [[ "$bundle_file" == "base" ]]; then bundle_files=("${PACKAGES_DIR}/Brewfile") elif [[ -f "${PACKAGES_DIR}/Brewfile.${bundle_file}" ]]; then bundle_files=("${PACKAGES_DIR}/Brewfile.${bundle_file}") else print_error "Unknown bundle: $bundle_file" print_info "Available: base, aws, ecmascript, k8s, terraform, work" return 1 fi
for target_bundle in "${bundle_files[@]}"; do if [[ ! -f "$target_bundle" ]]; then continue fi
local filename=$(basename "$target_bundle") local bundle_name if [[ "$filename" == "Brewfile" ]]; then bundle_name="base" else bundle_name="${filename#Brewfile.}" fi
echo -e "\n${BOLD}${bundle_name^} packages (${filename}):${RESET}"
local brew_packages=() local cask_packages=()
while IFS= read -r line; do [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line// }" ]] && continue
if [[ "$line" =~ ^brew[[:space:]]+\"([^\"]+)\" ]]; then brew_packages+=("${BASH_REMATCH[1]}") elif [[ "$line" =~ ^cask[[:space:]]+\"([^\"]+)\" ]]; then cask_packages+=("${BASH_REMATCH[1]}") fi done < "$target_bundle"
if [[ ${#brew_packages[@]} -gt 0 ]]; then echo -e " ${BOLD}Brew formulas (${#brew_packages[@]}):${RESET}" for package in "${brew_packages[@]}"; do if echo "$installed_formulas" | grep -q "^${package}$"; then print_success " $package" else print_error " $package (not installed)" fi done fi
if [[ ${#cask_packages[@]} -gt 0 ]]; then echo -e " ${BOLD}Casks (${#cask_packages[@]}):${RESET}" for package in "${cask_packages[@]}"; do if echo "$installed_casks" | grep -q "^${package}$"; then print_success " $package" else print_error " $package (not installed)" fi done fi
if [[ ${#brew_packages[@]} -eq 0 && ${#cask_packages[@]} -eq 0 ]]; then print_info " No packages found" fi done}
cmd_package_help() { echo -e "${BOLD}${SCRIPT_NAME} package${RESET} - Package management commands" echo "" echo -e "${BOLD}USAGE:${RESET}" echo " ${SCRIPT_NAME} package [SUBCOMMAND] [OPTIONS]" echo "" echo -e "${BOLD}SUBCOMMANDS:${RESET}" echo " add NAME [CONTEXT] [--cask] Add package to bundle and install it" echo " remove NAME [CONTEXT] Remove package from bundle and optionally uninstall" echo " update [NAME] Update packages from all Brewfiles (or specific package)" echo " list [CONTEXT] List packages in bundle files (default)" echo " help Show this help message" echo "" echo -e "${BOLD}PARAMETERS:${RESET}" echo " NAME Package name (required for add/remove, optional for update)" echo " CONTEXT Bundle: base, aws, ecmascript, k8s, terraform, work" echo " (add defaults to base, remove defaults to auto-search)" echo " --cask Force cask type for add command (auto-detects by default)" echo "" echo -e "${BOLD}EXAMPLES:${RESET}" echo " ${SCRIPT_NAME} package list # List all packages" echo " ${SCRIPT_NAME} package list base # List base packages only" echo " ${SCRIPT_NAME} package list k8s # List k8s packages only" echo " ${SCRIPT_NAME} package add git # Add git formula to base (auto-detect)" echo " ${SCRIPT_NAME} package add helm k8s # Add helm formula to k8s bundle" echo " ${SCRIPT_NAME} package add docker --cask # Add docker cask to base" echo " ${SCRIPT_NAME} package add docker work --cask # Add docker cask to work" echo " ${SCRIPT_NAME} package remove git # Remove git from any bundle" echo " ${SCRIPT_NAME} package remove docker base # Remove docker from base bundle only" echo " ${SCRIPT_NAME} package remove helm k8s # Remove helm from k8s bundle" echo " ${SCRIPT_NAME} package update # Update all packages from Brewfiles" echo " ${SCRIPT_NAME} package update git # Update specific package" echo "" echo -e "${BOLD}NOTES:${RESET}" echo " - Package type is auto-detected (formula first, then cask)" echo " - Use --cask to force cask type when auto-detect chooses wrong" echo " - Packages are kept sorted alphabetically within each type" echo " - Adding a package installs it immediately and adds to bundle" echo " - Removing a package removes from bundle and optionally uninstalls" echo " - Update checks all Brewfiles and updates installed packages only" echo " - Available bundles: base, aws, ecmascript, k8s, terraform, work" echo ""}
cmd_help() { echo -e "${BOLD}${SCRIPT_NAME}${RESET} - Dotfiles management tool" echo "Version: ${VERSION}" echo "" echo -e "${BOLD}USAGE:${RESET}" echo " ${SCRIPT_NAME} [OPTIONS] COMMAND [ARGS]" echo "" echo -e "${BOLD}COMMANDS:${RESET}" echo " init Initialize and install dotfiles" echo " update Update dotfiles and packages" echo " doctor Run diagnostics and check installation" echo " package Package management commands (add, remove, list)" echo " check-packages Check which packages are installed/missing" echo " retry-failed Retry failed package installations" echo " gen-ssh-key Generate SSH key for GitHub/GitLab with email" echo " vscode-sync Sync installed VS Code extensions to extensions.json" echo " stow Create symlinks for dotfiles using GNU Stow" echo " link Install dot command globally (create symlink in PATH)" echo " unlink Uninstall global dot command (remove symlink)" echo " edit Open dotfiles in VS Code" echo " help Show this help message (default)" echo "" echo -e "${BOLD}OPTIONS:${RESET}" echo " --skip-ssh Skip SSH key generation" echo " --version Show version information" echo " -h, --help Show this help message" echo "" echo -e "${BOLD}EXAMPLES:${RESET}" echo " ${SCRIPT_NAME} init # Full initialization" echo " ${SCRIPT_NAME} init --skip-ssh # Initialize without SSH setup" echo " ${SCRIPT_NAME} update # Update everything" echo " ${SCRIPT_NAME} doctor # Check installation health" echo " ${SCRIPT_NAME} package list # List all packages" echo " ${SCRIPT_NAME} package add git # Add git package to base bundle" echo " ${SCRIPT_NAME} package update # Update all packages" echo " ${SCRIPT_NAME} package remove docker # Remove docker from bundles" echo " ${SCRIPT_NAME} check-packages # See package installation status" echo " ${SCRIPT_NAME} retry-failed # Retry any failed installations" echo " ${SCRIPT_NAME} gen-ssh-key # Generate SSH key (prompts for email)" echo " ${SCRIPT_NAME} gen-ssh-key user@github.com # Generate SSH key with email" echo " ${SCRIPT_NAME} vscode-sync # Update extensions.json from installed extensions" echo " ${SCRIPT_NAME} stow # Create symlinks for dotfiles" echo " ${SCRIPT_NAME} link # Install dot command globally in PATH" echo "" echo -e "${BOLD}CONFIGURATION:${RESET}" echo " Dotfiles directory: ${DOTFILES_DIR}" echo " Packages directory: ${PACKAGES_DIR}" echo " Home directory: ${HOME_DIR}" echo "" echo -e "${BOLD}NOTES:${RESET}" echo " - Package installation is resilient to failures" echo " - Failed packages are logged and can be retried later" echo " - SHA verification is disabled for better reliability" echo " - OpenCode CLI installed via native installer (with brew/bun/npm fallback)" echo " - Doctor command checks all critical development tools" echo " - Summary command uses AI to analyze and summarize git commits" echo ""}
# Main functionmain() { # Parse global options while [[ $# -gt 0 ]]; do case "$1" in --skip-ssh) export SKIP_SSH=true shift ;; --version) echo "${SCRIPT_NAME} version ${VERSION}" exit 0 ;; -h|--help) cmd_help exit 0 ;; *) break ;; esac done # Get command local cmd="${1:-help}" shift || true # Execute command case "$cmd" in init) cmd_init "$@" ;; update) cmd_update "$@" ;; doctor) cmd_doctor "$@" ;; package) cmd_package "$@" ;; check-packages) cmd_check_packages "$@" ;; retry-failed) cmd_retry_failed "$@" ;; gen-ssh-key) cmd_gen_ssh_key "$@" ;; vscode-sync) cmd_vscode_sync "$@" ;; stow) cmd_stow "$@" ;; link) cmd_link "$@" ;; unlink) cmd_unlink "$@" ;; edit) cmd_edit "$@" ;; help) cmd_help ;; *) print_error "Unknown command: $cmd" echo "Run '${SCRIPT_NAME} help' for usage information" exit 1 ;; esac}
# Run main functionmain "$@"