Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Last active August 28, 2025 08:26
Show Gist options
  • Select an option

  • Save soltrinox/2e8b51e79c4a9f38b7f5268841831fe2 to your computer and use it in GitHub Desktop.

Select an option

Save soltrinox/2e8b51e79c4a9f38b7f5268841831fe2 to your computer and use it in GitHub Desktop.
OSX.MacBook.Pro.M4.Max.setup.sh

Development Environment Setup Scripts

This directory contains scripts to set up a comprehensive development environment for macOS MacBook Pro M4 Max (Apple Silicon).

🚀 Quick Start

Option 1: Interactive Menu (Recommended)

./scripts/quick_setup.sh

This provides an interactive menu to choose your setup option.

Option 2: Direct Commands

# Full setup (all tools and languages)
./scripts/setup.sh

# Docker-only setup (skip to Docker section)
./scripts/setup.sh --docker

# Docker setup with error recovery
./scripts/setup_docker.sh

📋 Available Scripts

1. setup.sh - Main Setup Script

  • Purpose: Complete development environment installation
  • Duration: 30-60 minutes
  • Includes: All development tools, languages, and configurations
  • Options:
    • ./setup.sh - Full setup
    • ./setup.sh --docker - Skip to Docker section
    • ./setup.sh --help - Show help

2. setup_docker.sh - Docker-Only Script

  • Purpose: Docker setup with error handling and recovery
  • Duration: 10-20 minutes
  • Features:
    • Docker daemon health checks
    • Automatic Docker Desktop startup
    • Error troubleshooting
    • ARM64 image building

3. quick_setup.sh - Interactive Launcher

  • Purpose: User-friendly menu for setup options
  • Features:
    • Easy selection of setup type
    • System status checking
    • Help and troubleshooting info

🐳 Docker Setup Options

If You Want to Skip Previous Installations

Option A: Use the Main Script with Docker Flag

./scripts/setup.sh --docker

This skips all previous phases and goes directly to Docker configuration.

Option B: Use the Dedicated Docker Script

./scripts/setup_docker.sh

This is the recommended option if you're having Docker issues or want focused Docker setup.

🔧 Troubleshooting Docker Issues

Common Docker Error: "Cannot connect to the Docker daemon"

1. Check Docker Desktop Status

# Check if Docker Desktop is running
ps aux | grep -i docker

# Check Docker socket
ls -la /var/run/docker.sock

2. Start Docker Desktop

# Start Docker Desktop manually
open -a Docker

# Wait for it to start (may take 1-2 minutes)

3. Use the Recovery Script

./scripts/setup_docker.sh

This script will:

  • Check Docker health
  • Attempt to start Docker Desktop
  • Provide troubleshooting information
  • Handle common Docker errors

Docker Build Issues

Legacy Builder Deprecation Warning

If you see: "The legacy builder is deprecated and will be removed in a future release"

Solution: The script automatically detects and uses buildx when available. If you're still seeing this warning:

  1. Update Docker Desktop to the latest version
  2. The script will automatically install and use buildx

ARM64 Build Issues

The script automatically:

  • Uses --platform linux/arm64 flag
  • Falls back to legacy builder if buildx is unavailable
  • Provides clear error messages for troubleshooting

📁 Script Structure

scripts/
├── setup.sh              # Main setup script
├── setup_docker.sh       # Docker-only setup with recovery
├── quick_setup.sh        # Interactive launcher
└── README.md             # This file

🎯 Setup Phases

The main setup script runs in phases:

  1. System Foundation - macOS optimization, Rosetta 2, Xcode CLI tools
  2. Package Management - Homebrew installation and configuration
  3. Version Management - ASDF for language version control
  4. Development Tools - Core development utilities
  5. AI/ML Development - PyTorch, TensorFlow, Jupyter
  6. iOS Development - Xcode tools, CocoaPods, Fastlane
  7. Web Development - Node.js, package managers
  8. Container Tools - Docker, Kubernetes tools
  9. Networking & Security - Network tools, security utilities
  10. Editors & Terminal - VS Code, Warp terminal
  11. Final Setup & Docker - Docker configuration and image building

🚨 Error Handling

If Setup Fails

  1. Check Logs:

    # Setup log
    cat ~/SETUP.LOG.md
    
    # Error log
    cat ~/SETUP_ERRORS.log
    
    # System report
    cat ~/SYSTEM.REPORT.md
  2. Run Specific Sections:

    # Docker only
    ./scripts/setup.sh --docker
    
    # Docker with recovery
    ./scripts/setup_docker.sh
  3. Check System Status:

    ./scripts/quick_setup.sh
    # Choose option 4: Check System Status

Recovery Options

  • Docker Issues: Use ./scripts/setup_docker.sh
  • Partial Failures: Check logs and run specific sections
  • System Issues: Verify system requirements and dependencies

📊 System Requirements

  • OS: macOS 12.0+ (Monterey or later)
  • Architecture: Apple Silicon (M1/M2/M3/M4 series)
  • Memory: 8GB+ RAM recommended
  • Storage: 20GB+ free space
  • Network: Internet connection for downloads
  • Privileges: Admin privileges for system tools

🔄 Post-Setup

After successful setup:

  1. Restart Terminal: source ~/.zshrc
  2. Verify Installation: asdf list
  3. Test Docker: docker run -it --rm --platform linux/arm64 custom-dev-image-arm64
  4. Check Tools: python3 --version, node --version, go version

📞 Support

Documentation

  • Setup Log: ~/SETUP.LOG.md
  • Error Log: ~/SETUP_ERRORS.log
  • System Report: ~/SYSTEM.REPORT.md

Common Commands

# Check what's installed
asdf list

# Check Docker status
docker info

# Check system resources
df -h
vm_stat

# View setup logs
cat ~/SETUP.LOG.md

Getting Help

  1. Check the generated logs and reports
  2. Use the interactive launcher: ./scripts/quick_setup.sh
  3. Run specific sections as needed
  4. Check system requirements and dependencies

Note: These scripts are designed to be safe and can be run multiple times. They will skip already installed components and continue from where they left off.

Multi-stage build for ARM64

FROM --platform=linux/arm64 alpine:latest AS base

Install system dependencies

RUN apk update && apk add --no-cache
bash
curl
git
build-base
openssl-dev
zlib-dev
readline-dev
libffi-dev
pkgconfig
cmake
ninja
llvm
&& rm -rf /var/cache/apk/*

Install Python and pip (Alpine-friendly approach)

RUN apk add --no-cache python3 py3-pip

Install Node.js

RUN apk add --no-cache nodejs npm

Install Go

RUN apk add --no-cache go

Install Rust

RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y ENV PATH="/root/.cargo/bin:${PATH}"

Set working directory

WORKDIR /workspace

Default command

CMD ["/bin/bash"]

#!/usr/bin/env bash
# =============================================================================
# macOS MacBook Pro M4 Max Development Environment Setup Script
# =============================================================================
#
# This script sets up a comprehensive development environment optimized for:
# - Apple Silicon (ARM64) architecture
# - AI/ML development with GPU acceleration
# - iOS mobile development
# - Modern web development
# - DevOps and infrastructure management
#
# =============================================================================
# CONFIGURATION TABLE
# =============================================================================
#
# | Category | Tools/Features | Status |
# |-------------------|--------------------------------------------------|---------|
# | SYSTEM | macOS optimization, Rosetta 2, ARM64 detection | ✅ |
# | PACKAGE MANAGER | Homebrew with ARM64 paths | ✅ |
# | SHELLS | bash, zsh, fish with universal config | ✅ |
# | TERMINAL | Warp with AI features and custom themes | ✅ |
# | VERSION MANAGER | asdf for 25+ languages and tools (primary) | ✅ |
# | PYTHON | Virtual environments, pipenv, poetry, pip-tools | ✅ |
# | AI/ML | PyTorch (MPS), TensorFlow (Metal), Jupyter | ✅ |
# | AI/ML TOOLS | MLflow, Weights & Biases, Hugging Face | ✅ |
# | AI/ML LIBRARIES | scikit-learn, OpenCV, pandas, numpy, scipy | ✅ |
# | iOS DEVELOPMENT | Xcode CLI tools, CocoaPods, Fastlane | ✅ |
# | iOS TOOLS | SwiftLint, SwiftFormat, iOS Simulator | ✅ |
# | WEB DEVELOPMENT | Node.js, Yarn, pnpm, Deno, Bun | ✅ |
# | DATABASES | PostgreSQL, MySQL, Redis, MongoDB, SQLite | ✅ |
# | CONTAINERS | Docker, Docker Compose, Kubernetes | ✅ |
# | INFRASTRUCTURE | Terraform, Helm, kubectl, Istio | ✅ |
# | NETWORKING | nmap, Wireshark, curl, jq, yq | ✅ |
# | SECURITY | OpenSSL, GPG, SSH tools, pass | ✅ |
# | BUILD TOOLS | CMake, Ninja, Bazel, Gradle, Maven | ✅ |
# | LANGUAGES | Go, Rust, Elixir, Haskell, OCaml, Clojure | ✅ |
# | EDITORS | VS Code extensions, Neovim | ✅ |
# | SHELL ENHANCEMENT | Oh My Zsh, completions, syntax highlighting | ✅ |
# | PROJECT TEMPLATES | AI/ML projects, iOS apps, development structure | ✅ |
# | ALIASES | 100+ development shortcuts and functions | ✅ |
# | PERFORMANCE | GPU acceleration, Metal support, M4 Max optim. | ✅ |
#
# =============================================================================
# FEATURES OVERVIEW
# =============================================================================
#
# 🚀 PERFORMANCE OPTIMIZATIONS
# - GPU acceleration for AI/ML workloads
# - Metal support for TensorFlow and PyTorch
# - ARM64-optimized builds and packages
# - Parallel processing capabilities
#
# 🧠 AI/ML DEVELOPMENT
# - PyTorch with MPS (Metal Performance Shaders)
# - TensorFlow with Metal acceleration
# - Jupyter Lab and Notebook integration
# - MLflow for experiment tracking
# - Hugging Face ecosystem
# - Computer vision and NLP tools
#
# 📱 iOS DEVELOPMENT
# - Xcode Command Line Tools
# - iOS Simulator setup
# - CocoaPods and Fastlane integration
# - Swift code quality tools
# - Device management utilities
#
# 🐳 CONTAINER & CLOUD
# - Docker with ARM64 support
# - Kubernetes cluster management
# - Infrastructure as Code (Terraform)
# - Service mesh tools (Istio, Linkerd)
#
# 🎨 DEVELOPMENT EXPERIENCE
# - Warp terminal with AI features
# - Universal shell configuration
# - 100+ development aliases
# - Project templates and structure
# - VS Code extensions
#
# 🔧 SYSTEM INTEGRATION
# - Homebrew package management
# - asdf version management
# - Python virtual environments
# - Shell completions and syntax highlighting
#
# =============================================================================
# USAGE INSTRUCTIONS
# =============================================================================
#
# 1. Make script executable: chmod +x scripts/setup.sh
# 2. Run setup: ./scripts/setup.sh
# 3. Restart terminal or source: source ~/.zshrc
# 4. Verify installation: asdf list
# 5. Start development: jl (Jupyter Lab), ai (AI projects), ios (iOS projects)
#
# =============================================================================
# REQUIREMENTS
# =============================================================================
#
# - macOS 12.0+ (Monterey or later)
# - Apple Silicon Mac (M1/M2/M3/M4 series)
# - Internet connection for package downloads
# - Admin privileges for system tools
# - Xcode from App Store (for iOS development)
#
# =============================================================================
# AUTHOR & VERSION
# =============================================================================
#
# Author: Enhanced setup script for macOS M4 Max
# Version: 2.0.0
# Last Updated: $(date)
#
# =============================================================================
set -e
# =============================================================================
# CONFIGURATION VARIABLES
# =============================================================================
ASDF_DIR="$HOME/.asdf"
TOOL_VERSIONS=".tool-versions"
DOCKER_COMPOSE_VERSION="1.29.2"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Logging and error tracking
SETUP_LOG="$HOME/SETUP.LOG.md"
SYSTEM_REPORT="$HOME/SYSTEM.REPORT.md"
ERROR_LOG="$HOME/SETUP_ERRORS.log"
INSTALLATION_STATUS=()
FAILED_INSTALLS=()
SUCCESSFUL_INSTALLS=()
SKIPPED_INSTALLS=()
START_TIME=$(date +%s)
# Latest versions optimized for ARM64
PYTHON_VERSION="latest"
NODEJS_VERSION="latest"
GOLANG_VERSION="latest"
RUST_VERSION="latest"
RUBY_VERSION="latest"
JAVA_VERSION="latest"
# =============================================================================
# CORE FUNCTIONS
# =============================================================================
# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================
print_status() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# =============================================================================
# LOGGING AND ERROR RECOVERY FUNCTIONS
# =============================================================================
log_entry() {
local level="$1"
local message="$2"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
case "$level" in
"INFO")
echo -e "${BLUE}[INFO]${NC} $message"
echo "## ℹ️ INFO - $timestamp" >> "$SETUP_LOG"
echo "$message" >> "$SETUP_LOG"
echo "" >> "$SETUP_LOG"
;;
"SUCCESS")
echo -e "${GREEN}[SUCCESS]${NC} $message"
echo "## ✅ SUCCESS - $timestamp" >> "$SETUP_LOG"
echo "$message" >> "$SETUP_LOG"
echo "" >> "$SETUP_LOG"
;;
"WARNING")
echo -e "${YELLOW}[WARNING]${NC} $message"
echo "## ⚠️ WARNING - $timestamp" >> "$SETUP_LOG"
echo "$message" >> "$SETUP_LOG"
echo "" >> "$SETUP_LOG"
;;
"ERROR")
echo -e "${RED}[ERROR]${NC} $message"
echo "## ❌ ERROR - $timestamp" >> "$SETUP_LOG"
echo "$message" >> "$SETUP_LOG"
echo "" >> "$SETUP_LOG"
echo "$timestamp - ERROR: $message" >> "$ERROR_LOG"
;;
"SKIP")
echo -e "${PURPLE}[SKIP]${NC} $message"
echo "## ⏭️ SKIP - $timestamp" >> "$SETUP_LOG"
echo "$message" >> "$SETUP_LOG"
echo "" >> "$SETUP_LOG"
;;
esac
}
log_installation_status() {
local component="$1"
local status="$2"
local details="$3"
case "$status" in
"SUCCESS")
SUCCESSFUL_INSTALLS+=("$component")
log_entry "SUCCESS" "$component: $details"
;;
"FAILED")
FAILED_INSTALLS+=("$component")
log_entry "ERROR" "$component: $details"
;;
"SKIPPED")
SKIPPED_INSTALLS+=("$component")
log_entry "SKIP" "⏭️ $component: $details"
;;
esac
INSTALLATION_STATUS+=("$component:$status:$details")
}
initialize_logging() {
log_entry "INFO" "🚀 Starting macOS MacBook Pro M4 Max Development Environment Setup"
log_entry "INFO" "Script started at: $(date)"
log_entry "INFO" "System: $(uname -s) $(uname -m)"
log_entry "INFO" "User: $USER"
log_entry "INFO" "Home: $HOME"
# Create log headers
cat > "$SETUP_LOG" << 'EOF'
# macOS Development Environment Setup Log
This log tracks the installation and configuration of your development environment.
## Setup Information
- **Script**: setup.sh
- **Target**: macOS MacBook Pro M4 Max
- **Architecture**: Apple Silicon (ARM64)
- **Start Time**: $(date)
## Installation Progress
EOF
# Create error log
cat > "$ERROR_LOG" << 'EOF'
# Setup Error Log
This file contains detailed error information from the setup process.
EOF
# Create system report template
cat > "$SYSTEM_REPORT" << 'EOF'
# macOS Development Environment System Report
## Overview
This report documents your complete development environment setup, including all installed tools, configurations, and usage instructions.
## System Information
- **Operating System**: macOS
- **Architecture**: Apple Silicon (ARM64)
- **Setup Date**: $(date)
- **Setup Duration**: Calculating...
## Installed Components
### Core System Tools
- **Status**: Pending installation
- **Location**: Various system directories
- **Configuration**: System-wide
### Development Languages
- **Status**: Pending installation
- **Management**: ASDF version manager
- **Configuration**: User-specific
### Development Tools
- **Status**: Pending installation
- **Configuration**: User-specific
### AI/ML Development
- **Status**: Pending installation
- **Configuration**: User-specific
### iOS Development
- **Status**: Pending installation
- **Configuration**: User-specific
## Usage Instructions
*To be populated after installation*
## Update Instructions
*To be populated after installation*
## Uninstall Instructions
*To be populated after installation*
## Troubleshooting
*To be populated after installation*
EOF
}
safe_execute() {
local function_name="$1"
local description="$2"
local max_retries="${3:-3}"
local retry_count=0
log_entry "INFO" "🔄 Executing: $description"
while [ $retry_count -lt $max_retries ]; do
if "$function_name"; then
log_installation_status "$function_name" "SUCCESS" "$description completed successfully"
return 0
else
retry_count=$((retry_count + 1))
if [ $retry_count -lt $max_retries ]; then
log_entry "WARNING" "⚠️ $description failed (attempt $retry_count/$max_retries), retrying..."
sleep 2
else
log_entry "ERROR" "$description failed after $max_retries attempts"
log_installation_status "$function_name" "FAILED" "$description failed after $max_retries attempts"
# Log the failure but continue with remaining installations
log_entry "WARNING" "Continuing with remaining installations despite $description failure"
return 1
fi
fi
done
}
generate_final_report() {
local end_time=$(date +%s)
local duration=$((end_time - START_TIME))
local duration_formatted=$(printf '%02d:%02d:%02d' $((duration/3600)) $((duration%3600/60)) $((duration%60)))
log_entry "INFO" "📊 Generating final installation report..."
# Update system report with final information
cat >> "$SYSTEM_REPORT" << EOF
## Installation Summary
- **Total Duration**: $duration_formatted
- **Successful Installations**: ${#SUCCESSFUL_INSTALLS[@]}
- **Failed Installations**: ${#FAILED_INSTALLS[@]}
- **Skipped Installations**: ${#SKIPPED_INSTALLS[@]}
## Detailed Installation Status
### ✅ Successful Installations (${#SUCCESSFUL_INSTALLS[@]})
EOF
for install in "${SUCCESSFUL_INSTALLS[@]}"; do
echo "- $install" >> "$SYSTEM_REPORT"
done
if [ ${#FAILED_INSTALLS[@]} -gt 0 ]; then
cat >> "$SYSTEM_REPORT" << EOF
### ❌ Failed Installations (${#FAILED_INSTALLS[@]})
EOF
for install in "${FAILED_INSTALLS[@]}"; do
echo "- $install" >> "$SYSTEM_REPORT"
done
fi
if [ ${#SKIPPED_INSTALLS[@]} -gt 0 ]; then
cat >> "$SYSTEM_REPORT" << EOF
### ⏭️ Skipped Installations (${#SKIPPED_INSTALLS[@]})
EOF
for install in "${SKIPPED_INSTALLS[@]}"; do
echo "- $install" >> "$SYSTEM_REPORT"
done
fi
# Add comprehensive usage instructions
cat >> "$SYSTEM_REPORT" << 'EOF'
## 🚀 Usage Instructions
### Quick Start Commands
```bash
# Check your environment
asdf list # List all installed languages
source ~/.zshrc # Reload shell configuration
echo $PATH # Verify PATH is set correctly
# Start development
jl # Launch Jupyter Lab
warp # Open Warp terminal
code . # Open VS Code in current directory
```
### Language Management
```bash
# ASDF commands
asdf list # Show all installed versions
asdf current # Show current global versions
asdf global python 3.11.0 # Set global Python version
asdf local nodejs 18.0.0 # Set local Node.js version for project
asdf install python 3.12.0 # Install specific Python version
asdf uninstall python 3.10.0 # Remove specific version
```
### Project Setup
```bash
# Python projects
cd ~/AI-Projects
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# Node.js projects
cd ~/Projects
npm init -y
npm install express
# Go projects
cd ~/Projects
go mod init myproject
go run main.go
```
## 🔄 Update Instructions
### System Updates
```bash
# Update Homebrew
brew update
brew upgrade
# Update ASDF
asdf update
asdf plugin update --all
# Update Python packages
pip install --upgrade pip
pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U
# Update Node.js packages
npm update -g
npm outdated -g
```
### Language Updates
```bash
# Update specific languages
asdf install python latest
asdf global python latest
asdf install nodejs latest
asdf global nodejs latest
asdf install golang latest
asdf global golang latest
```
### Tool Updates
```bash
# Update development tools
pip install --upgrade black flake8 mypy
npm install -g @vue/cli@latest
go install golang.org/x/tools/cmd/goimports@latest
```
## 🗑️ Uninstall Instructions
### Remove Specific Languages
```bash
# Remove Python
asdf uninstall python 3.10.0
asdf plugin remove python
# Remove Node.js
asdf uninstall nodejs 18.0.0
asdf plugin remove nodejs
# Remove Go
asdf uninstall golang 1.20.0
asdf plugin remove golang
```
### Remove Development Tools
```bash
# Remove Python packages
pip uninstall black flake8 mypy
# Remove Node.js packages
npm uninstall -g @vue/cli
# Remove Go tools
go clean -i
```
### Complete Environment Removal
```bash
# Remove ASDF
rm -rf ~/.asdf
# Remove from shell config files
# Remove Homebrew packages
brew uninstall --force $(brew list)
# Remove configuration files
rm -rf ~/.zshrc ~/.bashrc ~/.bash_profile
rm -rf ~/.oh-my-zsh
rm -rf ~/.warp
```
## ⚙️ Configuration Files
### Shell Configuration
- **Zsh**: `~/.zshrc`
- **Bash**: `~/.bashrc`, `~/.bash_profile`
- **Universal**: `~/.shell_common`
### ASDF Configuration
- **Versions**: `~/.tool-versions`
- **Installations**: `~/.asdf/`
### Python Configuration
- **Virtual Environments**: `~/.virtualenvs/`
- **Pip Config**: `~/.pip/pip.conf`
- **Poetry Config**: `~/.config/pypoetry/`
### Warp Terminal Configuration
- **Settings**: `~/.warp/settings.yaml`
- **Keybindings**: `~/.warp/keybindings.yaml`
- **Themes**: `~/.warp/themes/`
### VS Code Configuration
- **User Settings**: `~/Library/Application Support/Code/User/settings.json`
- **Extensions**: `~/.vscode/extensions/`
## 🔧 Troubleshooting
### Common Issues
#### ASDF Not Found
```bash
# Add to shell config
echo '. "$HOME/.asdf/asdf.sh"' >> ~/.zshrc
source ~/.zshrc
```
#### Python Virtual Environment Issues
```bash
# Reinstall virtualenvwrapper
pip install --user virtualenvwrapper
# Check WORKON_HOME is set correctly
echo $WORKON_HOME
```
#### Homebrew Path Issues
```bash
# For Apple Silicon
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc
```
#### Warp Terminal Issues
```bash
# Reset Warp configuration
rm -rf ~/.warp
# Reinstall Warp
brew reinstall --cask warp
```
### Performance Optimization
```bash
# Check system resources
htop
iostat 1
# Monitor disk usage
df -h
# Check memory usage
vm_stat
```
### Log Files
- **Setup Log**: `~/SETUP.LOG.md`
- **Error Log**: `~/SETUP_ERRORS.log`
- **System Report**: `~/SYSTEM.REPORT.md`
## 📞 Support
### Documentation
- **ASDF**: https://asdf-vm.com/
- **Homebrew**: https://brew.sh/
- **Warp**: https://warp.dev/
- **VS Code**: https://code.visualstudio.com/
### Community
- **GitHub Issues**: Check the respective tool repositories
- **Stack Overflow**: Search for specific error messages
- **Discord/Slack**: Join tool-specific communities
---
*This report was generated automatically by setup.sh on $(date)*
EOF
log_entry "SUCCESS" "📊 Final system report generated: $SYSTEM_REPORT"
log_entry "INFO" "📋 Setup log available: $SETUP_LOG"
if [ ${#FAILED_INSTALLS[@]} -gt 0 ]; then
log_entry "WARNING" "⚠️ Some installations failed. Check $ERROR_LOG for details."
fi
}
# =============================================================================
# SYSTEM DETECTION & SETUP
# =============================================================================
check_architecture() {
local arch=$(uname -m)
if [[ "$arch" == "arm64" ]]; then
print_success "Detected Apple Silicon (ARM64) architecture"
return 0
elif [[ "$arch" == "x86_64" ]]; then
print_warning "Detected Intel architecture - consider using Rosetta 2 for some tools"
return 1
else
print_error "Unsupported architecture: $arch"
exit 1
fi
}
verify_dependencies() {
print_status "Verifying critical system dependencies..."
local missing_deps=()
# Check for essential system commands only (not programming languages)
local essential_commands=("git" "curl" "brew")
for cmd in "${essential_commands[@]}"; do
if ! command -v "$cmd" &>/dev/null; then
missing_deps+=("$cmd")
fi
done
# Check for essential directories
if [ ! -d "$HOME" ]; then
missing_deps+=("HOME directory")
fi
if [ ! -w "$HOME" ]; then
missing_deps+=("HOME directory write permissions")
fi
# Check for Xcode Command Line Tools (required for many Homebrew packages)
if ! xcode-select -p &>/dev/null; then
missing_deps+=("Xcode Command Line Tools")
fi
# Report missing dependencies
if [ ${#missing_deps[@]} -gt 0 ]; then
print_error "Missing critical system dependencies:"
for dep in "${missing_deps[@]}"; do
echo " - $dep"
done
print_error "Please install missing dependencies before continuing"
return 1
fi
print_success "All critical system dependencies verified"
return 0
}
install_rosetta() {
if [[ "$(uname -m)" == "arm64" ]]; then
print_status "Checking Rosetta 2 installation..."
if ! /usr/bin/pgrep -q oahd; then
print_status "Installing Rosetta 2..."
/usr/sbin/softwareupdate --install-rosetta --agree-to-license
print_success "Rosetta 2 installed successfully"
else
print_success "Rosetta 2 already installed"
fi
fi
}
install_xcode_cli_tools() {
print_status "Checking Xcode Command Line Tools installation..."
if ! xcode-select -p &>/dev/null; then
print_status "Installing Xcode Command Line Tools..."
xcode-select --install
# Wait for installation to complete
print_status "Waiting for Xcode Command Line Tools installation to complete..."
while ! xcode-select -p &>/dev/null; do
sleep 5
print_status "Still waiting for Xcode Command Line Tools installation..."
done
print_success "Xcode Command Line Tools installed successfully"
else
print_success "Xcode Command Line Tools already installed"
fi
}
# =============================================================================
# PACKAGE MANAGEMENT
# =============================================================================
install_homebrew() {
if ! command -v brew &>/dev/null; then
print_status "Installing Homebrew..."
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Add Homebrew to PATH for ARM64
if [[ "$(uname -m)" == "arm64" ]]; then
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$HOME/.zshrc"
eval "$(/opt/homebrew/bin/brew shellenv)"
fi
print_success "Homebrew installed successfully"
else
print_success "Homebrew already installed"
brew update
fi
}
# =============================================================================
# HOMEBREW PACKAGE VALIDATION
# =============================================================================
validate_brew_packages() {
print_status "Validating Homebrew packages for installation..."
# List of packages that might cause issues
local problematic_packages=(
"jazzup" # Known to cause issues with checkmarks
"ucloud" # Alternative to gcloud that might be suggested
"hcloud" # Alternative to gcloud that might be suggested
"buck" # Deprecated build system, no longer available
)
for package in "${problematic_packages[@]}"; do
if brew search "$package" &>/dev/null; then
print_warning "Found potentially problematic package: $package"
print_status "This package will be skipped to prevent installation issues"
fi
done
print_success "Package validation completed"
}
# =============================================================================
# WARP TERMINAL INSTALLATION
# =============================================================================
install_warp_terminal() {
print_status "Installing Warp terminal..."
# Check if Warp is already installed via Homebrew
if brew list --cask warp &>/dev/null; then
print_success "Warp terminal already installed via Homebrew"
return 0
fi
# Check if Warp is currently running and close it
if pgrep -f "Warp" >/dev/null; then
print_status "Warp is currently running, closing it for installation..."
pkill -f "Warp" 2>/dev/null || true
sleep 2
fi
# Check if Warp.app already exists in Applications folder
if [ -d "/Applications/Warp.app" ]; then
print_status "Warp.app found in Applications folder"
# Check if it's a valid app
if [ -f "/Applications/Warp.app/Contents/MacOS/Warp" ]; then
print_success "Warp terminal already installed in Applications folder"
# Check if it's a recent version
local warp_version
warp_version=$(defaults read "/Applications/Warp.app/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo "unknown")
print_status "Warp version: $warp_version"
# Try to link it to Homebrew for easier management
if ! brew list --cask warp &>/dev/null; then
print_status "Linking existing Warp.app to Homebrew for easier management..."
brew link --cask warp --force 2>/dev/null || true
print_success "Warp linked to Homebrew for easier management"
fi
return 0
else
print_warning "Warp.app found but appears to be corrupted, removing..."
sudo rm -rf "/Applications/Warp.app"
fi
fi
# Check if there are any other Warp installations
if find /Applications -name "*Warp*" -type d 2>/dev/null | grep -q .; then
print_status "Found other Warp-related installations, cleaning up..."
sudo find /Applications -name "*Warp*" -type d -exec rm -rf {} + 2>/dev/null || true
print_success "Cleaned up existing Warp installations"
fi
# Now install Warp via Homebrew
print_status "Installing Warp terminal via Homebrew..."
if brew install --cask warp; then
print_success "Warp terminal installed successfully"
else
print_warning "Failed to install Warp via Homebrew"
print_status "You can download Warp manually from https://warp.dev"
return 1
fi
}
# =============================================================================
# SAFE HOMEBREW INSTALLATION
# =============================================================================
safe_brew_install() {
local packages=("$@")
local failed_packages=()
for package in "${packages[@]}"; do
print_status "Installing $package..."
# Check if package is already installed
if brew list "$package" &>/dev/null; then
print_success "$package already installed"
continue
fi
# Try to install the package (macOS doesn't have timeout command)
if brew install "$package" 2>&1 | tee -a "$SETUP_LOG"; then
print_success "$package installed successfully"
else
print_warning "Failed to install $package"
failed_packages+=("$package")
fi
done
# Report any failed packages
if [ ${#failed_packages[@]} -gt 0 ]; then
print_warning "The following packages failed to install: ${failed_packages[*]}"
print_status "You can try installing them manually later with: brew install <package_name>"
fi
return 0 # Always return success to prevent script from exiting
}
install_core_system_dependencies() {
print_status "Installing core system dependencies via Homebrew..."
# =============================================================================
# CORE SYSTEM TOOLS (Install first - no dependencies)
# =============================================================================
print_status "Installing core system tools..."
safe_brew_install git curl wget openssl readline sqlite3 xz zlib tcl-tk gpg libffi pkg-config cmake ninja llvm
print_success "Core system tools installed"
# =============================================================================
# DEVELOPMENT UTILITIES (Depend on core tools)
# =============================================================================
print_status "Installing development utilities..."
safe_brew_install jq yq htop tree ripgrep fd bat exa fzf tmux neovim
print_success "Development utilities installed"
# =============================================================================
# SHELL ENHANCEMENTS (Depend on zsh)
# =============================================================================
print_status "Installing shell enhancements..."
safe_brew_install fish starship powerlevel10k antigen zinit oh-my-zsh zsh-completions zsh-syntax-highlighting zsh-autosuggestions zsh-history-substring-search zsh-navigation-tools
print_success "Shell enhancements installed"
# =============================================================================
# TERMINAL APPLICATIONS (Install last - may have complex dependencies)
# =============================================================================
print_status "Installing terminal applications..."
# Install Warp terminal
install_warp_terminal
print_success "Core system dependencies installed successfully"
}
# =============================================================================
# ADDITIONAL TOOLS & DEPENDENCIES
# =============================================================================
install_additional_tools() {
print_status "Installing additional tools and dependencies..."
# Additional useful tools
safe_brew_install docker docker-compose kubectl helm terraform awscli azure-cli postgresql redis
# MongoDB needs special handling
if ! brew list mongodb/brew/mongodb-community &>/dev/null; then
brew tap mongodb/brew
brew install mongodb/brew/mongodb-community
print_success "MongoDB installed"
else
print_success "MongoDB already installed"
fi
# Install gcloud CLI as a cask (correct package name)
if ! brew list --cask gcloud-cli &>/dev/null; then
brew install --cask gcloud-cli
print_success "Google Cloud CLI installed"
else
print_success "Google Cloud CLI already installed"
fi
# AI/ML Development Tools
print_status "Installing AI/ML development tools..."
# Note: Core Python and pip packages will be installed via ASDF
# These are additional tools that work with Python
safe_brew_install opencv
# cmake, ninja, llvm are already installed in core tools
print_status "Python packages will be installed via pip after ASDF Python setup"
print_status "Core Python installation is managed by ASDF version manager"
# Mobile Development (iOS) Tools
print_status "Installing iOS mobile development tools..."
safe_brew_install cocoapods fastlane carthage xcodegen sourcery swiftlint swiftformat jazzy appledoc ios-deploy libimobiledevice ideviceinstaller ideviceinfo idevicepair ideviceprovision idevicescreenshot idevicesyslog idevicebackup2 idevicebackup idevicecrashreport ideviceimagemounter
# Development and Build Tools
print_status "Installing development and build tools..."
safe_brew_install cmake ninja make autoconf automake libtool pkg-config meson bazel gradle maven ant sbt
# Note: Core languages and package managers (go, elixir, erlang, ocaml, kotlin, scala, clojure)
# are managed by ASDF for version control, not installed via Homebrew
print_status "Core programming languages will be managed by ASDF for version control"
# Database and Storage Tools
print_status "Installing database and storage tools..."
safe_brew_install mysql mariadb sqlite cassandra elasticsearch neo4j arangodb couchdb riak memcached etcd consul vault nomad terraform packer vagrant kubernetes-cli minikube kind k3s istioctl linkerd
# Note: postgresql, redis, mongodb, docker, docker-compose, helm, kubectl are already installed in earlier sections
# Network and Security Tools
print_status "Installing network and security tools..."
safe_brew_install nmap wireshark tcpdump netcat socat httpie xq iotop nethogs iftop bmon speedtest-cli mtr traceroute dig nslookup whois gnupg pass ssh-copy-id sshfs rsync scp sftp telnet ftp lftp ncftp aria2 youtube-dl yt-dlp
# Note: curl, wget, jq, yq, htop, openssl, gpg are already installed in earlier sections
# Shell and terminal tools (remove duplicates)
print_status "Installing additional shell and terminal tools..."
safe_brew_install fish starship powerlevel10k antigen zinit oh-my-zsh zsh-completions zsh-syntax-highlighting zsh-autosuggestions zsh-history-substring-search zsh-navigation-tools
# Install Warp terminal
install_warp_terminal
print_success "Additional tools and dependencies installed successfully"
}
# =============================================================================
# PYTHON CLEANUP & SYSTEM MANAGEMENT
# =============================================================================
uninstall_system_python() {
print_status "Checking for non-ASDF Python installations..."
# Check for Homebrew Python installations
if brew list python &>/dev/null; then
print_status "Uninstalling Homebrew Python..."
brew uninstall --force python [email protected] [email protected] [email protected] [email protected] 2>/dev/null || true
print_success "Homebrew Python packages removed"
fi
# Check for system Python symlinks that might conflict
if [ -L "/usr/local/bin/python" ] || [ -L "/usr/local/bin/python3" ]; then
print_status "Removing conflicting Python symlinks..."
sudo rm -f /usr/local/bin/python /usr/local/bin/python3 /usr/local/bin/pip /usr/local/bin/pip3 2>/dev/null || true
print_success "Conflicting Python symlinks removed"
fi
# Check for pip installations that might conflict
if command -v pip &>/dev/null && ! command -v asdf &>/dev/null; then
print_status "Removing system pip installations..."
sudo rm -f /usr/local/bin/pip /usr/local/bin/pip3 2>/dev/null || true
print_success "System pip installations removed"
fi
print_success "Python cleanup completed"
}
# =============================================================================
# VERSION MANAGEMENT (ASDF)
# =============================================================================
install_asdf() {
# First, uninstall any non-ASDF Python installations
uninstall_system_python
if [ ! -d "$ASDF_DIR" ]; then
print_status "Installing asdf..."
git clone https://github.com/asdf-vm/asdf.git "$ASDF_DIR" --branch v0.14.0
# Verify installation
if [ ! -f "$ASDF_DIR/asdf.sh" ]; then
print_error "asdf installation failed"
exit 1
fi
else
print_success "asdf already installed"
fi
# Shell integration
local shell_configs=("$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile")
for config in "${shell_configs[@]}"; do
if [ -f "$config" ]; then
if ! grep -q '. "$HOME/.asdf/asdf.sh"' "$config" 2>/dev/null; then
print_status "Adding asdf to $config"
echo -e '\n# asdf version manager' >> "$config"
echo '. "$HOME/.asdf/asdf.sh"' >> "$config"
echo '. "$HOME/.asdf/completions/asdf.bash"' >> "$config"
fi
fi
done
# Load asdf immediately
. "$ASDF_DIR/asdf.sh"
print_success "asdf loaded successfully"
# Ensure shell configuration is updated
print_status "Updating shell configuration..."
# Update .zshrc if it exists
if [ -f "$HOME/.zshrc" ]; then
if ! grep -q '. "$HOME/.asdf/asdf.sh"' "$HOME/.zshrc"; then
echo -e '\n# asdf version manager' >> "$HOME/.zshrc"
echo '. "$HOME/.asdf/asdf.sh"' >> "$HOME/.zshrc"
echo '. "$HOME/.asdf/completions/asdf.bash"' >> "$HOME/.zshrc"
print_success "Updated .zshrc with ASDF configuration"
fi
fi
# Update .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
if ! grep -q '. "$HOME/.asdf/asdf.sh"' "$HOME/.bashrc"; then
echo -e '\n# asdf version manager' >> "$HOME/.bashrc"
echo '. "$HOME/.asdf/asdf.sh"' >> "$HOME/.bashrc"
echo '. "$HOME/.asdf/completions/asdf.bash"' >> "$HOME/.bashrc"
print_success "Updated .bashrc with ASDF configuration"
fi
fi
# Update .profile if it exists
if [ -f "$HOME/.profile" ]; then
if ! grep -q '. "$HOME/.asdf/asdf.sh"' "$HOME/.profile"; then
echo -e '\n# asdf version manager' >> "$HOME/.profile"
echo '. "$HOME/.asdf/asdf.sh"' >> "$HOME/.profile"
echo '. "$HOME/.asdf/completions/asdf.bash"' >> "$HOME/.profile"
print_success "Updated .profile with ASDF configuration"
fi
fi
}
install_plugin() {
local plugin="$1"
if ! asdf plugin list | grep -q "$plugin"; then
print_status "Adding plugin: $plugin"
asdf plugin add "$plugin"
else
print_success "Plugin $plugin already added"
fi
}
install_language_plugins() {
print_status "Installing comprehensive language plugins for ASDF..."
# =============================================================================
# CORE LANGUAGE PLUGINS (Essential for development)
# =============================================================================
print_status "Installing core language plugins..."
install_plugin python
install_plugin nodejs
install_plugin golang
install_plugin rust
install_plugin ruby
install_plugin java
# =============================================================================
# WEB DEVELOPMENT PLUGINS
# =============================================================================
print_status "Installing web development language plugins..."
install_plugin php
install_plugin elixir
install_plugin erlang
install_plugin crystal
# =============================================================================
# FUNCTIONAL PROGRAMMING PLUGINS
# =============================================================================
print_status "Installing functional programming language plugins..."
install_plugin haskell
install_plugin ocaml
install_plugin clojure
install_plugin scala
# =============================================================================
# SYSTEMS PROGRAMMING PLUGINS
# =============================================================================
print_status "Installing systems programming language plugins..."
install_plugin nim
install_plugin zig
# =============================================================================
# DATA SCIENCE PLUGINS
# =============================================================================
print_status "Installing data science language plugins..."
install_plugin R
install_plugin julia
# =============================================================================
# SCRIPTING & EMBEDDED PLUGINS
# =============================================================================
print_status "Installing scripting and embedded language plugins..."
install_plugin lua
install_plugin kotlin
# =============================================================================
# ADDITIONAL TOOL PLUGINS
# =============================================================================
print_status "Installing additional tool plugins..."
install_plugin terraform
install_plugin kubectl
install_plugin helm
install_plugin awscli
# Note: gcloud is installed via Homebrew cask, not ASDF plugin
install_plugin azure-cli
install_plugin docker
install_plugin docker-compose
install_plugin postgres
install_plugin redis
install_plugin mongodb
install_plugin mysql
install_plugin sqlite
print_success "Comprehensive language plugins installed successfully"
print_status "Total plugins available: $(asdf plugin list | wc -l)"
}
get_latest_version() {
local plugin="$1"
local version
version=$(asdf latest "$plugin" 2>/dev/null || echo "latest")
echo "$version"
}
install_language_versions() {
print_status "Installing language versions..."
# Get latest versions
PYTHON_VERSION=$(get_latest_version python)
NODEJS_VERSION=$(get_latest_version nodejs)
GOLANG_VERSION=$(get_latest_version golang)
RUST_VERSION=$(get_latest_version rust)
RUBY_VERSION=$(get_latest_version ruby)
JAVA_VERSION=$(get_latest_version java)
print_status "Installing Python $PYTHON_VERSION..."
asdf install python "$PYTHON_VERSION"
print_status "Installing Node.js $NODEJS_VERSION..."
asdf install nodejs "$NODEJS_VERSION"
print_status "Installing Go $GOLANG_VERSION..."
asdf install golang "$GOLANG_VERSION"
print_status "Installing Rust $RUST_VERSION..."
asdf install rust "$RUST_VERSION"
print_status "Installing Ruby $RUBY_VERSION..."
asdf install ruby "$RUBY_VERSION"
print_status "Installing Java $JAVA_VERSION..."
asdf install java "$JAVA_VERSION"
# Install additional language versions
print_status "Installing additional language versions..."
# Web development languages
asdf install php latest
asdf install elixir latest
asdf install erlang latest
# Functional programming languages
asdf install haskell latest
asdf install ocaml latest
asdf install clojure latest
# Data science languages
asdf install R latest
asdf install julia latest
# Systems programming
asdf install nim latest
asdf install zig latest
# Create .tool-versions file
cat > "$TOOL_VERSIONS" << EOF
python $PYTHON_VERSION
nodejs $NODEJS_VERSION
golang $GOLANG_VERSION
rust $RUST_VERSION
ruby $RUBY_VERSION
java $JAVA_VERSION
EOF
# Set global versions
asdf global python "$PYTHON_VERSION"
asdf global nodejs "$NODEJS_VERSION"
asdf global golang "$GOLANG_VERSION"
asdf global rust "$RUST_VERSION"
asdf global ruby "$RUBY_VERSION"
asdf global java "$JAVA_VERSION"
print_success "All language versions installed and set globally"
# =============================================================================
# VERIFY ASDF INSTALLATIONS
# =============================================================================
print_status "Verifying ASDF language installations..."
# Show installed versions
print_status "Installed language versions:"
asdf list
# Show global versions
print_status "Global language versions:"
asdf current
# Show available plugins
print_status "Available ASDF plugins:"
asdf plugin list
print_success "ASDF language verification complete"
# Additional ASDF configuration verification
print_status "Verifying ASDF configuration..."
# Check if ASDF is in PATH
if command -v asdf >/dev/null 2>&1; then
print_success "ASDF is available in PATH"
else
print_warning "ASDF not in PATH, attempting to reload shell configuration"
# Try to reload ASDF
if [ -f "$HOME/.asdf/asdf.sh" ]; then
. "$HOME/.asdf/asdf.sh"
if command -v asdf >/dev/null 2>&1; then
print_success "ASDF reloaded successfully"
else
print_error "Failed to reload ASDF"
fi
fi
fi
# Verify ASDF plugins are working
print_status "Testing ASDF plugin functionality..."
if asdf plugin list >/dev/null 2>&1; then
print_success "ASDF plugins are working correctly"
else
print_error "ASDF plugins are not working correctly"
fi
# Verify that key programming languages are available
print_status "Verifying programming language availability..."
local languages=("python" "nodejs" "golang" "rust" "ruby" "java")
local missing_languages=()
for lang in "${languages[@]}"; do
if asdf current "$lang" &>/dev/null 2>&1; then
local version
version=$(asdf current "$lang" | awk '{print $2}')
print_success "$lang is available (version: $version)"
else
print_warning "$lang is not yet installed via ASDF"
missing_languages+=("$lang")
fi
done
if [ ${#missing_languages[@]} -gt 0 ]; then
print_status "The following languages will be installed in the next phase: ${missing_languages[*]}"
fi
}
# =============================================================================
# PYTHON PACKAGE INSTALLATION (via pip after ASDF Python setup)
# =============================================================================
install_python_packages() {
print_status "Installing comprehensive Python packages via pip..."
# Ensure we're using the ASDF Python
if command -v asdf >/dev/null 2>&1 && asdf current python >/dev/null 2>&1; then
print_status "Using ASDF Python for package installation"
# Core data science and ML packages
print_status "Installing data science and ML packages..."
pip install \
numpy \
pandas \
scipy \
matplotlib \
seaborn \
plotly \
scikit-learn \
jupyter \
jupyterlab \
ipython \
requests \
beautifulsoup4 \
lxml \
sqlalchemy \
psycopg2-binary \
pymongo \
redis \
celery \
fastapi \
uvicorn \
flask \
django \
pytest \
pytest-cov \
black \
flake8 \
mypy \
isort \
pre-commit
# AI/ML specific packages
print_status "Installing AI/ML packages..."
pip install \
torch \
torchvision \
torchaudio \
tensorflow \
transformers \
datasets \
accelerate \
diffusers \
optuna \
ray \
dask \
vaex \
polars \
huggingface-hub \
streamlit \
gradio
# Development and build tools
print_status "Installing development tools..."
pip install \
virtualenv \
virtualenvwrapper \
pipenv \
poetry \
pip-tools \
pipdeptree \
wheel \
setuptools \
build \
twine
print_success "Python packages installed successfully via ASDF Python"
else
print_warning "ASDF Python not detected, skipping pip package installation"
print_status "Please ensure ASDF Python is installed first"
fi
}
# =============================================================================
# DEVELOPMENT ENVIRONMENT SETUP
# =============================================================================
setup_development_environment() {
print_status "Setting up development environment..."
# Create development directories
mkdir -p "$HOME/Projects"
mkdir -p "$HOME/Development"
mkdir -p "$HOME/Downloads/Development"
# Install additional Python packages
print_status "Installing Python development packages..."
pip install --user \
black \
flake8 \
mypy \
pytest \
pytest-cov \
ipython \
jupyter \
pandas \
numpy \
requests \
beautifulsoup4 \
fastapi \
uvicorn
# Install Python virtual environment tools
print_status "Installing Python virtual environment tools..."
pip install --user \
virtualenv \
virtualenvwrapper \
pipenv \
poetry \
pip-tools \
pipdeptree
# Install Node.js global packages
print_status "Installing Node.js global packages..."
npm install -g \
yarn \
pnpm \
typescript \
ts-node \
nodemon \
eslint \
prettier \
@vue/cli \
create-react-app \
expo-cli
# Install Go tools
print_status "Installing Go development tools..."
go install \
golang.org/x/tools/cmd/goimports@latest \
golang.org/x/tools/cmd/godoc@latest \
github.com/golangci/golangci-lint/cmd/golangci-lint@latest \
github.com/go-delve/delve/cmd/dlv@latest
# Install Rust tools
print_status "Installing Rust development tools..."
cargo install \
cargo-edit \
cargo-watch \
cargo-audit \
cargo-outdated \
ripgrep \
fd-find \
bat \
exa \
tokei
print_success "Development environment setup complete"
}
# =============================================================================
# SHELL ENVIRONMENT SETUP
# =============================================================================
setup_shell_environment() {
print_status "Setting up shell environment..."
# Install Oh My Zsh if not already installed
if [ ! -d "$HOME/.oh-my-zsh" ]; then
print_status "Installing Oh My Zsh..."
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
fi
# Install color bash
print_status "Installing color bash..."
brew install bash bash-completion@2
# Add bash to /etc/shells if not already there
if ! grep -q "/opt/homebrew/bin/bash" /etc/shells 2>/dev/null; then
echo "/opt/homebrew/bin/bash" | sudo tee -a /etc/shells
fi
# Create universal shell configuration that works for both bash and zsh
local universal_config="$HOME/.shell_common"
cat > "$universal_config" << 'EOF'
# Universal shell configuration for bash and zsh
# This file is sourced by both .bashrc and .zshrc
# Colors for output
export RED='\033[0;31m'
export GREEN='\033[0;32m'
export YELLOW='\033[1;33m'
export BLUE='\033[0;34m'
export PURPLE='\033[0;35m'
export CYAN='\033[0;36m'
export NC='\033[0m' # No Color
# Color prompt
if [ -n "$ZSH_VERSION" ]; then
# Zsh prompt
PROMPT='%{$BLUE%}%n@%m%{$NC%}:%{$GREEN%}%~%{$NC%}$ '
RPROMPT='%{$YELLOW%}[%T]%{$NC%}'
elif [ -n "$BASH_VERSION" ]; then
# Bash prompt
PS1='\[$BLUE\]\u@\h\[$NC\]:\[$GREEN\]\w\[$NC\]\$ '
fi
# Universal aliases
alias ll='exa -la 2>/dev/null || ls -la'
alias la='exa -a 2>/dev/null || ls -a'
alias l='exa -l 2>/dev/null || ls -l'
alias cat='bat 2>/dev/null || cat'
alias grep='rg 2>/dev/null || grep --color=auto'
alias find='fd 2>/dev/null || find'
alias top='htop 2>/dev/null || top'
alias vim='nvim 2>/dev/null || vim'
alias vi='nvim 2>/dev/null || vi'
# Development aliases
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gl='git pull'
alias gco='git checkout'
alias gcb='git checkout -b'
alias gb='git branch'
alias gd='git diff'
alias glog='git log --oneline --graph --decorate'
alias gst='git stash'
alias gstp='git stash pop'
# ASDF version management shortcuts
alias al='asdf list'
alias ac='asdf current'
alias apl='asdf plugin list'
alias ai='asdf install'
alias au='asdf uninstall'
alias ag='asdf global'
alias alo='asdf local'
alias as='asdf shell'
alias ar='asdf reshim'
alias aup='asdf plugin update --all'
alias aupg='asdf update'
alias av='asdf version'
alias ah='asdf help'
# Python virtual environment aliases
alias va='source venv/bin/activate'
alias vd='deactivate'
alias vc='python -m venv venv'
alias vr='rm -rf venv'
alias vp='pip list'
alias vpi='pip install'
alias vpu='pip uninstall'
alias vpf='pip freeze > requirements.txt'
alias vpi='pip install -r requirements.txt'
# Docker aliases
alias d='docker'
alias dc='docker-compose'
alias dps='docker ps'
alias dpsa='docker ps -a'
alias di='docker images'
alias drm='docker rm'
alias drmi='docker rmi'
alias dex='docker exec -it'
alias dlogs='docker logs'
# Kubernetes aliases
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kl='kubectl logs'
alias ka='kubectl apply'
alias kd='kubectl delete'
alias kpf='kubectl port-forward'
# System aliases
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'
alias ~='cd ~'
alias -- -='cd -'
alias c='clear'
alias h='history'
alias j='jobs -l'
alias path='echo -e ${PATH//:/\\n}'
alias now='date +"%T"'
alias nowtime=now
alias nowdate='date +"%d-%m-%Y"'
alias ports='netstat -tulanp'
alias header='curl -I'
alias headerc='curl -I --compress'
# Network aliases
alias myip='curl http://ipecho.net/plain; echo'
alias localip='ifconfig | grep "inet " | grep -v 127.0.0.1'
alias ping='ping -c 5'
alias fastping='ping -c 100 -s.2'
# File management aliases
alias mkdir='mkdir -pv'
alias cp='cp -iv'
alias mv='mv -iv'
alias rm='rm -iv'
alias ln='ln -iv'
alias chmod='chmod -v'
alias chown='chown -v'
# Path additions
export PATH="$HOME/.local/bin:$PATH"
export PATH="$HOME/go/bin:$PATH"
export PATH="$HOME/.cargo/bin:$PATH"
# Environment variables
export EDITOR='nvim'
export VISUAL='nvim'
export PAGER='bat 2>/dev/null || less'
export TERM='xterm-256color'
# FZF configuration
export FZF_DEFAULT_OPTS='--height 40% --layout=reverse --border'
export FZF_DEFAULT_COMMAND='fd --type f --hidden --exclude .git 2>/dev/null || find . -type f -not -path "*/\.*"'
# History configuration
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoreboth:erasedups
export HISTIGNORE="ls:cd:pwd:clear:history:exit"
# Shell options
set -o vi # Vi mode for command line editing
bindkey -v # Enable vi mode for zsh
# Completion
if [ -n "$ZSH_VERSION" ]; then
autoload -U compinit
compinit
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
elif [ -n "$BASH_VERSION" ]; then
if [ -f /opt/homebrew/etc/bash_completion ]; then
. /opt/homebrew/etc/bash_completion
fi
fi
EOF
# Create bash configuration
print_status "Setting up bash configuration..."
cat > "$HOME/.bashrc" << EOF
# Bash configuration
# Source universal shell configuration
if [ -f "\$HOME/.shell_common" ]; then
source "\$HOME/.shell_common"
fi
# Bash-specific configurations
if [ -f /opt/homebrew/etc/bash_completion ]; then
source /opt/homebrew/etc/bash_completion
fi
# asdf version manager
if [ -f "\$HOME/.asdf/asdf.sh" ]; then
source "\$HOME/.asdf/asdf.sh"
source "\$HOME/.asdf/completions/asdf.bash"
fi
# Python virtual environments
export WORKON_HOME="\$HOME/.virtualenvs"
export PROJECT_HOME="\$HOME/Projects"
if [ -f "\$(asdf where python 2>/dev/null)/bin/virtualenvwrapper.sh" ]; then
export VIRTUALENVWRAPPER_PYTHON="\$(asdf where python)/bin/python"
export VIRTUALENVWRAPPER_VIRTUALENV="\$(asdf where python)/bin/virtualenv"
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--python=\$(asdf where python)/bin/python"
source "\$(asdf where python)/bin/virtualenvwrapper.sh"
fi
# Poetry configuration
export POETRY_VIRTUALENVS_IN_PROJECT=true
export POETRY_CACHE_DIR="\$HOME/.cache/pypoetry"
# Pipenv configuration
export PIPENV_VENV_IN_PROJECT=true
export PIPENV_CACHE_DIR="\$HOME/.cache/pipenv"
EOF
# Create zsh configuration
print_status "Setting up zsh configuration..."
cat > "$HOME/.zshrc" << EOF
# Zsh configuration
# Source universal shell configuration
if [ -f "\$HOME/.shell_common" ]; then
source "\$HOME/.shell_common"
fi
# Oh My Zsh configuration
export ZSH="\$HOME/.oh-my-zsh"
ZSH_THEME="robbyrussell"
plugins=(git docker kubectl helm terraform aws)
source \$ZSH/oh-my-zsh.sh
# asdf version manager
if [ -f "\$HOME/.asdf/asdf.sh" ]; then
source "\$HOME/.asdf/asdf.sh"
source "\$HOME/.asdf/completions/asdf.bash"
fi
# Python virtual environments
export WORKON_HOME="\$HOME/.virtualenvs"
export PROJECT_HOME="\$HOME/Projects"
if [ -f "\$(asdf where python 2>/dev/null)/bin/virtualenvwrapper.sh" ]; then
export VIRTUALENVWRAPPER_PYTHON="\$(asdf where python)/bin/python"
export VIRTUALENVWRAPPER_VIRTUALENV="\$(asdf where python)/bin/virtualenv"
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--python=\$(asdf where python)/bin/python"
source "\$(asdf where python)/bin/virtualenvwrapper.sh"
fi
# Poetry configuration
export POETRY_VIRTUALENVS_IN_PROJECT=true
export POETRY_CACHE_DIR="\$HOME/.cache/pypoetry"
# Pipenv configuration
export PIPENV_VENV_IN_PROJECT=true
export PIPENV_CACHE_DIR="\$HOME/.cache/pipenv"
# Zsh completions
if type brew &>/dev/null; then
FPATH="\$(brew --prefix)/share/zsh/site-functions:\${FPATH}"
autoload -Uz compinit
compinit
fi
EOF
# Create bash profile
print_status "Setting up bash profile..."
cat > "$HOME/.bash_profile" << 'EOF'
# Bash profile
# Source .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
source "$HOME/.bashrc"
fi
# Source .profile if it exists
if [ -f "$HOME/.profile" ]; then
source "$HOME/.profile"
fi
EOF
# Create shell switching function
print_status "Setting up shell switching..."
cat >> "$HOME/.shell_common" << 'EOF'
# Shell switching function
switch_shell() {
local shell="$1"
case "$shell" in
"bash"|"b")
if command -v bash &>/dev/null; then
echo "Switching to bash..."
exec bash
else
echo "Bash not found. Installing..."
brew install bash
exec bash
fi
;;
"zsh"|"z")
if command -v zsh &>/dev/null; then
echo "Switching to zsh..."
exec zsh
else
echo "Zsh not found. Installing..."
brew install zsh
exec zsh
fi
;;
"fish"|"f")
if command -v fish &>/dev/null; then
echo "Switching to fish..."
exec fish
else
echo "Fish not found. Installing..."
brew install fish
exec fish
fi
;;
*)
echo "Usage: switch_shell [bash|zsh|fish]"
echo "Shortcuts: b, z, f"
echo "Available shells:"
echo " bash - $(which bash 2>/dev/null || echo 'Not installed')"
echo " zsh - $(which zsh 2>/dev/null || echo 'Not installed')"
echo " fish - $(which fish 2>/dev/null || echo 'Not installed')"
;;
esac
}
# Quick shell switching aliases
alias b='switch_shell bash'
alias z='switch_shell zsh'
alias f='switch_shell fish'
# Show current shell info
alias shell='echo "Current shell: $SHELL" && echo "Shell version:" && $SHELL --version'
alias shells='echo "Available shells:" && cat /etc/shells'
EOF
print_success "Shell environment configured with universal support"
}
setup_git_configuration() {
print_status "Setting up Git configuration..."
# Set default Git configuration
git config --global init.defaultBranch main
git config --global pull.rebase false
git config --global core.editor nvim
git config --global core.autocrlf input
git config --global core.safecrlf warn
# Set up Git aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
print_success "Git configuration complete"
}
# =============================================================================
# PYTHON VIRTUAL ENVIRONMENTS
# =============================================================================
setup_python_virtual_environments() {
print_status "Setting up Python virtual environments..."
# Check if ASDF Python is available
if ! command -v asdf >/dev/null 2>&1; then
print_warning "ASDF not available, skipping virtual environment setup"
return 0
fi
if ! asdf current python >/dev/null 2>&1; then
print_warning "ASDF Python not available, skipping virtual environment setup"
return 0
fi
# Create virtual environment directories
mkdir -p "$HOME/.virtualenvs"
mkdir -p "$HOME/.local/share/virtualenvs"
# Get ASDF Python path
local python_path
python_path=$(asdf where python)
if [ ! -d "$python_path" ]; then
print_warning "ASDF Python path not found, skipping virtual environment setup"
return 0
fi
# Create sample virtual environments for common use cases
print_status "Creating sample virtual environments..."
# Create a general development environment
if [ -f "$python_path/bin/virtualenv" ]; then
print_status "Creating 'dev' virtual environment..."
if [ -d "$HOME/.virtualenvs/dev" ]; then
print_status "Removing existing 'dev' virtual environment..."
rm -rf "$HOME/.virtualenvs/dev"
fi
"$python_path/bin/virtualenv" "$HOME/.virtualenvs/dev"
if [ -f "$HOME/.virtualenvs/dev/bin/pip" ]; then
"$HOME/.virtualenvs/dev/bin/pip" install \
ipython \
jupyter \
black \
flake8 \
mypy \
pytest \
requests \
pandas \
numpy
print_success "Created 'dev' virtual environment"
else
print_warning "Failed to create 'dev' virtual environment"
fi
else
print_warning "virtualenv not found in ASDF Python, skipping environment creation"
fi
# Create a web development environment
if [ -f "$python_path/bin/virtualenv" ]; then
print_status "Creating 'web' virtual environment..."
if [ -d "$HOME/.virtualenvs/web" ]; then
print_status "Removing existing 'web' virtual environment..."
rm -rf "$HOME/.virtualenvs/web"
fi
"$python_path/bin/virtualenv" "$HOME/.virtualenvs/web"
if [ -f "$HOME/.virtualenvs/web/bin/pip" ]; then
"$HOME/.virtualenvs/web/bin/pip" install \
fastapi \
uvicorn \
django \
flask \
sqlalchemy \
alembic \
psycopg2-binary \
redis
print_success "Created 'web' virtual environment"
else
print_warning "Failed to create 'web' virtual environment"
fi
fi
# Create a data science environment
if [ -f "$python_path/bin/virtualenv" ]; then
print_status "Creating 'data' virtual environment..."
if [ -d "$HOME/.virtualenvs/data" ]; then
print_status "Removing existing 'data' virtual environment..."
rm -rf "$HOME/.virtualenvs/data"
fi
"$python_path/bin/virtualenv" "$HOME/.virtualenvs/data"
if [ -f "$HOME/.virtualenvs/data/bin/pip" ]; then
"$HOME/.virtualenvs/data/bin/pip" install \
jupyter \
pandas \
numpy \
matplotlib \
seaborn \
scikit-learn \
scipy \
plotly \
streamlit
print_success "Created 'data' virtual environment"
else
print_warning "Failed to create 'data' virtual environment"
fi
fi
# Configure Poetry
print_status "Configuring Poetry..."
if command -v poetry &>/dev/null; then
poetry config virtualenvs.in-project true
poetry config virtualenvs.path "$HOME/.virtualenvs"
print_success "Poetry configured"
fi
# Configure Pipenv
print_status "Configuring Pipenv..."
if command -v pipenv &>/dev/null; then
export PIPENV_VENV_IN_PROJECT=true
print_success "Pipenv configured"
fi
print_success "Python virtual environments setup complete"
}
create_dockerfile() {
print_status "Creating optimized Dockerfile for ARM64..."
cat > Dockerfile << 'EOF'
# Multi-stage build for ARM64
FROM --platform=linux/arm64 alpine:latest AS base
# Install system dependencies
RUN apk update && apk add --no-cache \
bash \
curl \
git \
build-base \
openssl-dev \
zlib-dev \
readline-dev \
libffi-dev \
pkgconfig \
cmake \
ninja \
llvm \
&& rm -rf /var/cache/apk/*
# Install Python
RUN apk add --no-cache python3 py3-pip \
&& python3 -m ensurepip --upgrade \
&& pip3 install --no-cache --upgrade pip --break-system-packages
# Install Node.js
RUN apk add --no-cache nodejs npm
# Install Go
RUN apk add --no-cache go
# Install Rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
# Set working directory
WORKDIR /workspace
# Default command
CMD ["/bin/bash"]
EOF
print_success "Dockerfile created for ARM64"
}
build_docker_image() {
print_status "Building Docker image for ARM64..."
# Check if Docker daemon is running
if ! docker info &>/dev/null; then
print_error "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"
print_status "Attempting to start Docker Desktop..."
# Try to start Docker Desktop if it's installed
if [ -d "/Applications/Docker.app" ]; then
print_status "Starting Docker Desktop..."
open -a Docker
# Wait for Docker to start
print_status "Waiting for Docker to start (this may take a minute)..."
local attempts=0
local max_attempts=60
while [ $attempts -lt $max_attempts ]; do
if docker info &>/dev/null; then
print_success "Docker daemon started successfully"
break
fi
sleep 2
attempts=$((attempts + 1))
print_status "Waiting for Docker... (attempt $attempts/$max_attempts)"
done
if [ $attempts -eq $max_attempts ]; then
print_error "Docker daemon failed to start after $max_attempts attempts"
print_warning "Skipping Docker image build. You can run the Docker setup later with: ./scripts/setup_docker.sh"
return 1
fi
else
print_error "Docker Desktop not found. Please install it from https://www.docker.com/products/docker-desktop/"
print_warning "Skipping Docker image build. You can run the Docker setup later with: ./scripts/setup_docker.sh"
return 1
fi
fi
# Check for Docker buildx (recommended over legacy builder)
if docker buildx version &>/dev/null; then
print_status "Using Docker buildx for better ARM64 support..."
if docker buildx build --platform linux/arm64 -t custom-dev-image-arm64 . --load; then
print_success "Docker image built successfully for ARM64 using buildx"
return 0
else
print_error "Failed to build Docker image with buildx"
return 1
fi
else
print_warning "Docker buildx not available, using legacy builder (deprecated)"
print_status "Consider updating Docker Desktop for better ARM64 support"
if docker build --platform linux/arm64 -t custom-dev-image-arm64 .; then
print_success "Docker image built successfully for ARM64"
return 0
else
print_error "Failed to build Docker image with legacy builder"
return 1
fi
fi
}
run_docker_container() {
print_status "Running Docker container..."
if docker run -it --rm --platform linux/arm64 custom-dev-image-arm64 /bin/bash; then
print_success "Docker container completed successfully"
else
print_warning "Docker container exited"
fi
}
setup_vscode_extensions() {
print_status "Setting up VS Code extensions..."
# Check if code command is available
if command -v code &>/dev/null; then
# Install useful extensions
code --install-extension ms-python.python
code --install-extension ms-vscode.vscode-typescript-next
code --install-extension golang.go
code --install-extension rust-lang.rust-analyzer
code --install-extension ms-vscode.vscode-json
code --install-extension bradlc.vscode-tailwindcss
code --install-extension esbenp.prettier-vscode
code --install-extension ms-vscode.vscode-eslint
code --install-extension ms-vscode-remote.remote-containers
code --install-extension ms-vscode-remote.remote-ssh
code --install-extension github.copilot
code --install-extension github.copilot-chat
print_success "VS Code extensions installed"
else
print_warning "VS Code not found, skipping extension installation"
fi
}
# =============================================================================
# iOS DEVELOPMENT SETUP
# =============================================================================
install_ios_dependencies() {
print_status "Installing iOS development dependencies via Homebrew..."
# =============================================================================
# CORE iOS DEVELOPMENT TOOLS
# =============================================================================
print_status "Installing core iOS development tools..."
brew install \
cocoapods \
fastlane \
carthage \
xcodegen \
sourcery \
swiftlint \
swiftformat \
jazzy \
appledoc \
ios-deploy \
libimobiledevice \
ideviceinstaller \
ideviceinfo \
idevicepair \
ideviceprovision \
idevicescreenshot \
idevicesyslog \
idevicebackup2 \
idevicebackup \
idevicecrashreport \
ideviceimagemounter
print_success "iOS development dependencies installed successfully"
}
setup_ios_development() {
print_status "Setting up iOS development environment..."
# Install Xcode Command Line Tools
print_status "Installing Xcode Command Line Tools..."
if ! xcode-select -p &>/dev/null; then
xcode-select --install
print_status "Xcode Command Line Tools installation started. Please complete the installation in the popup window."
print_status "After installation, run this script again to continue with iOS setup."
return 1
else
print_success "Xcode Command Line Tools already installed"
fi
# Install iOS Simulator
print_status "Setting up iOS Simulator..."
if ! xcrun simctl list &>/dev/null; then
print_warning "iOS Simulator not available. Please install Xcode from App Store first."
else
print_success "iOS Simulator available"
# List available simulators
print_status "Available iOS Simulators:"
xcrun simctl list devices available | grep "iPhone\|iPad" | head -10
fi
# Configure CocoaPods
print_status "Configuring CocoaPods..."
if command -v pod &>/dev/null; then
pod setup
print_success "CocoaPods configured"
fi
# Configure Fastlane
print_status "Configuring Fastlane..."
if command -v fastlane &>/dev/null; then
# Create Fastlane configuration directory
mkdir -p "$HOME/.fastlane"
# Create basic Fastlane configuration
cat > "$HOME/.fastlane/Appfile" << 'EOF'
# Fastlane Appfile
# This file contains the basic configuration for your app
app_identifier("com.yourcompany.yourapp") # The bundle identifier of your app
apple_id("[email protected]") # Your Apple email address
itc_team_id("123456789") # App Store Connect Team ID
team_id("ABC123DEF4") # Developer Portal Team ID
EOF
print_success "Fastlane configured with basic Appfile"
fi
# Create iOS development directory structure
print_status "Creating iOS development directory structure..."
mkdir -p "$HOME/iOS-Projects"
mkdir -p "$HOME/iOS-Projects/Examples"
mkdir -p "$HOME/iOS-Projects/Templates"
mkdir -p "$HOME/iOS-Projects/Libraries"
mkdir -p "$HOME/iOS-Projects/Playgrounds"
# Create sample iOS project template
local ios_template="$HOME/iOS-Projects/Templates/Basic-iOS-App"
mkdir -p "$ios_template"
cat > "$ios_template/README.md" << 'EOF'
# Basic iOS App Template
This is a basic iOS app template with common configurations.
## Features
- SwiftUI-based app
- CocoaPods integration
- Fastlane setup
- Basic project structure
## Usage
1. Copy this template to your desired location
2. Update bundle identifier and team information
3. Open in Xcode
4. Build and run
## Dependencies
- iOS 15.0+
- Xcode 13.0+
- Swift 5.5+
EOF
print_success "iOS development environment setup complete"
}
# =============================================================================
# AI/ML DEVELOPMENT SETUP
# =============================================================================
install_ai_ml_dependencies() {
print_status "Installing AI/ML development dependencies via Homebrew..."
# =============================================================================
# CORE AI/ML LIBRARIES (Install via Homebrew first)
# =============================================================================
print_status "Installing core AI/ML libraries..."
brew install \
python-tensorflow \
python-pytorch \
python-scikit-learn \
python-opencv \
python-jupyter \
python-matplotlib \
python-seaborn \
python-plotly \
python-streamlit \
python-gradio \
python-huggingface-hub \
python-transformers \
python-datasets \
python-accelerate \
python-diffusers \
python-optuna \
python-ray \
python-dask \
python-vaex \
python-polars \
python-pandas \
python-numpy \
python-scipy \
python-numba \
python-cython \
python-mypy \
python-black \
python-flake8 \
python-isort \
python-pre-commit \
python-poetry \
python-pipenv \
python-virtualenv \
python-virtualenvwrapper
print_success "AI/ML dependencies installed successfully"
}
setup_ai_development() {
print_status "Setting up AI/ML development environment..."
# Create AI development directories
mkdir -p "$HOME/AI-Projects"
mkdir -p "$HOME/AI-Projects/Models"
mkdir -p "$HOME/AI-Projects/Datasets"
mkdir -p "$HOME/AI-Projects/Experiments"
mkdir -p "$HOME/AI-Projects/Notebooks"
mkdir -p "$HOME/AI-Projects/APIs"
# Install additional AI/ML tools
print_status "Installing additional AI/ML tools..."
# Install PyTorch with MPS support for M4 Max
if command -v python3 &>/dev/null; then
print_status "Installing PyTorch with MPS support..."
pip3 install --user torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
# Install TensorFlow with Metal support
print_status "Installing TensorFlow with Metal support..."
pip3 install --user tensorflow-macos tensorflow-metal
# Install additional AI libraries
print_status "Installing additional AI libraries..."
pip3 install --user \
transformers \
datasets \
accelerate \
diffusers \
optimum \
sentence-transformers \
langchain \
openai \
anthropic \
cohere \
replicate \
modal \
streamlit \
gradio \
panel \
dash \
plotly \
bokeh \
altair \
folium \
geopandas \
shap \
lime \
interpret \
mlflow \
wandb \
comet-ml \
neptune \
optuna \
hyperopt \
optuna \
ray[tune] \
dask \
vaex \
polars \
duckdb \
sqlalchemy \
alembic \
psycopg2-binary \
pymongo \
redis \
celery \
flower \
airflow \
prefect \
dagster \
kubeflow \
seldon-core \
bentoml \
triton \
onnx \
onnxruntime \
tensorrt \
openvino \
tvm \
mlir \
iree \
xla \
jax \
flax \
haiku \
optax \
chex \
orbax-checkpoint \
tensorflow-probability \
edward2 \
pyro \
pymc \
arviz \
emcee \
corner \
bilby \
gwpy \
astropy \
sunpy \
heliopy \
plasmapy \
opencv-python \
pillow \
scikit-image \
imageio \
matplotlib \
seaborn \
plotly \
bokeh \
altair \
folium \
geopandas \
shapely \
fiona \
rasterio \
earthpy \
geemap \
xarray \
dask \
vaex \
polars \
duckdb \
sqlalchemy \
alembic \
psycopg2-binary \
pymongo \
redis \
celery \
flower \
airflow \
prefect \
dagster \
kubeflow \
seldon-core \
bentoml \
triton \
onnx \
onnxruntime \
tensorrt \
openvino \
tvm \
mlir \
iree \
xla \
jax \
flax \
haiku \
optax \
chex \
orbax-checkpoint
fi
# Create sample AI project structure
local ai_template="$HOME/AI-Projects/Templates/Basic-ML-Project"
mkdir -p "$ai_template"
cat > "$ai_template/README.md" << 'EOF'
# Basic ML Project Template
This is a basic machine learning project template with common configurations.
## Features
- Jupyter notebook setup
- MLflow experiment tracking
- Model versioning
- Data preprocessing pipeline
- Model evaluation metrics
## Structure
- `data/` - Raw and processed data
- `models/` - Trained models
- `notebooks/` - Jupyter notebooks
- `src/` - Source code
- `tests/` - Unit tests
- `requirements.txt` - Python dependencies
## Usage
1. Copy this template to your desired location
2. Install dependencies: `pip install -r requirements.txt`
3. Start Jupyter: `jupyter lab`
4. Begin your ML journey!
## Dependencies
- Python 3.8+
- Jupyter Lab
- MLflow
- Scikit-learn
- Pandas
- NumPy
EOF
# Create requirements.txt for AI projects
cat > "$ai_template/requirements.txt" << 'EOF'
# Core ML libraries
torch>=2.0.0
tensorflow-macos>=2.13.0
tensorflow-metal>=1.0.0
scikit-learn>=1.3.0
pandas>=2.0.0
numpy>=1.24.0
# Jupyter and visualization
jupyter>=1.0.0
jupyterlab>=4.0.0
matplotlib>=3.7.0
seaborn>=0.12.0
plotly>=5.15.0
# Experiment tracking
mlflow>=2.5.0
wandb>=0.15.0
# Data processing
opencv-python>=4.8.0
pillow>=10.0.0
scikit-image>=0.21.0
# Utilities
tqdm>=4.65.0
click>=8.1.0
pyyaml>=6.0
python-dotenv>=1.0.0
EOF
print_success "AI/ML development environment setup complete"
}
# =============================================================================
# WEB DEVELOPMENT TOOLS
# =============================================================================
install_web_development_tools() {
print_status "Installing web development tools..."
# =============================================================================
# CORE WEB DEVELOPMENT TOOLS (Package managers only)
# =============================================================================
print_status "Installing web development package managers..."
brew install \
yarn \
pnpm \
deno \
bun
# Note: Node.js is managed by ASDF for version control
print_status "Node.js will be managed by ASDF for version control"
print_success "Web development tools installed successfully"
}
# =============================================================================
# CONTAINER & CLOUD TOOLS
# =============================================================================
install_container_tools() {
print_status "Installing container and cloud tools..."
# =============================================================================
# CORE CONTAINER TOOLS (Runtime tools only)
# =============================================================================
print_status "Installing container runtime tools..."
brew install \
minikube \
kind \
k3s
# Note: Docker, kubectl, and helm are managed by ASDF for version control
print_status "Docker, kubectl, and helm will be managed by ASDF for version control"
print_success "Container tools installed successfully"
}
# =============================================================================
# DATABASE TOOLS
# =============================================================================
install_database_tools() {
print_status "Installing database tools..."
# =============================================================================
# CORE DATABASE TOOLS (Runtime services only)
# =============================================================================
print_status "Installing database runtime services..."
brew install \
cassandra \
elasticsearch \
neo4j \
arangodb \
couchdb \
riak \
memcached \
etcd \
consul \
vault \
nomad
# Note: Core databases (mysql, mariadb, postgresql, redis, mongodb)
# are managed by ASDF for version control and client tools
print_status "Core database clients will be managed by ASDF for version control"
print_success "Database tools installed successfully"
}
# =============================================================================
# INFRASTRUCTURE TOOLS
# =============================================================================
install_infrastructure_tools() {
print_status "Installing infrastructure tools..."
# =============================================================================
# CORE INFRASTRUCTURE TOOLS (Runtime tools only)
# =============================================================================
print_status "Installing infrastructure runtime tools..."
brew install \
packer \
vagrant \
istioctl \
linkerd
# Note: Terraform is managed by ASDF for version control
print_status "Terraform will be managed by ASDF for version control"
print_success "Infrastructure tools installed successfully"
}
# =============================================================================
# NETWORKING TOOLS
# =============================================================================
install_networking_tools() {
print_status "Installing networking tools..."
# =============================================================================
# CORE NETWORKING TOOLS
# =============================================================================
print_status "Installing core networking tools..."
brew install \
nmap \
wireshark \
tcpdump \
netcat \
socat \
httpie \
speedtest-cli \
mtr \
traceroute \
dig \
nslookup \
whois \
aria2 \
youtube-dl \
yt-dlp
print_success "Networking tools installed successfully"
}
# =============================================================================
# SECURITY TOOLS
# =============================================================================
install_security_tools() {
print_status "Installing security tools..."
# =============================================================================
# CORE SECURITY TOOLS
# =============================================================================
print_status "Installing core security tools..."
brew install \
gnupg \
pass \
ssh-copy-id \
sshfs \
rsync
print_success "Security tools installed successfully"
}
# =============================================================================
# BUILD TOOLS
# =============================================================================
install_build_tools() {
print_status "Installing build tools..."
# =============================================================================
# CORE BUILD TOOLS
# =============================================================================
print_status "Installing core build tools..."
safe_brew_install make autoconf automake libtool meson bazel gradle maven ant sbt
print_success "Build tools installed successfully"
}
# =============================================================================
# PROGRAMMING LANGUAGES
# =============================================================================
install_programming_languages() {
print_status "Installing programming languages..."
# =============================================================================
# CORE PROGRAMMING LANGUAGES (Build tools and package managers only)
# =============================================================================
print_status "Installing programming language build tools and package managers..."
brew install \
haskell-stack \
opam \
leiningen \
racket \
guile \
scheme \
lisp \
clisp \
sbcl \
chicken \
gambit-c \
mit-scheme
# Note: Core languages (go, elixir, erlang, ocaml, kotlin, scala, clojure)
# are managed by ASDF for version control
print_status "Core programming languages will be managed by ASDF for version control"
print_success "Programming language tools installed successfully"
}
# =============================================================================
# WARP TERMINAL SETUP
# =============================================================================
setup_warp_terminal() {
print_status "Setting up Warp terminal..."
# Create Warp configuration directory
local warp_config_dir="$HOME/.warp"
mkdir -p "$warp_config_dir"
# Create Warp settings file
local warp_settings="$warp_config_dir/settings.yaml"
cat > "$warp_settings" << 'EOF'
# Warp Terminal Configuration
# Optimized for macOS and development workflow
# Theme and appearance
theme: "Dracula"
font_family: "JetBrains Mono"
font_size: 14
font_weight: "Regular"
line_height: 1.2
cursor_style: "Block"
cursor_blink: true
# Performance optimizations
gpu_acceleration: true
vsync: true
max_fps: 60
renderer: "Vulkan"
# Terminal behavior
scrollback_size: 10000
scroll_on_output: false
scroll_on_tty_output: true
scroll_multiplier: 3
bell: "Disabled"
window_padding_x: 20
window_padding_y: 20
# Tab and window management
new_tab_cwd: "Current"
new_window_cwd: "Current"
startup_mode: "Window"
window_decorations: "Transparent"
background_opacity: 0.95
# Key bindings
key_bindings:
- action: "NewTab"
key: "Cmd+T"
- action: "CloseTab"
key: "Cmd+W"
- action: "NextTab"
key: "Cmd+Shift+]"
- action: "PreviousTab"
key: "Cmd+Shift+["
- action: "SplitVertical"
key: "Cmd+D"
- action: "SplitHorizontal"
key: "Cmd+Shift+D"
- action: "ClosePane"
key: "Cmd+Shift+W"
- action: "ToggleFullScreen"
key: "Cmd+Shift+F"
# AI features
ai_enabled: true
ai_suggestions: true
ai_autocomplete: true
ai_explanation: true
# Development integrations
git_integration: true
ssh_integration: true
docker_integration: true
kubernetes_integration: true
# Shell integration
shell_integration: true
auto_complete: true
auto_suggestions: true
syntax_highlighting: true
EOF
# Create Warp keybindings file
local warp_keybindings="$warp_config_dir/keybindings.yaml"
cat > "$warp_keybindings" << 'EOF'
# Custom Warp Keybindings
# Enhanced for development workflow
# Navigation
- action: "MoveToBeginningOfLine"
key: "Ctrl+A"
- action: "MoveToEndOfLine"
key: "Ctrl+E"
- action: "MoveToBeginningOfWord"
key: "Ctrl+Left"
- action: "MoveToEndOfWord"
key: "Ctrl+Right"
- action: "MoveToBeginningOfDocument"
key: "Cmd+Up"
- action: "MoveToEndOfDocument"
key: "Cmd+Down"
# Editing
- action: "DeleteWordBackward"
key: "Ctrl+W"
- action: "DeleteWordForward"
key: "Ctrl+D"
- action: "KillLine"
key: "Ctrl+U"
- action: "Yank"
key: "Ctrl+Y"
- action: "TransposeCharacters"
key: "Ctrl+T"
# Search and history
- action: "SearchBackward"
key: "Ctrl+R"
- action: "SearchForward"
key: "Ctrl+S"
- action: "HistorySearchBackward"
key: "Up"
- action: "HistorySearchForward"
key: "Down"
# Development shortcuts
- action: "ExecuteCommand"
key: "Ctrl+Shift+E"
command: "git status"
- action: "ExecuteCommand"
key: "Ctrl+Shift+G"
command: "git log --oneline -10"
- action: "ExecuteCommand"
key: "Ctrl+Shift+D"
command: "docker ps"
- action: "ExecuteCommand"
key: "Ctrl+Shift+K"
command: "kubectl get pods"
EOF
# Create Warp themes directory and add custom themes
local warp_themes_dir="$warp_config_dir/themes"
mkdir -p "$warp_themes_dir"
# Create a custom development theme
local custom_theme="$warp_themes_dir/development.yaml"
cat > "$custom_theme" << 'EOF'
# Custom Development Theme for Warp
# Optimized for long coding sessions
name: "Development"
colors:
# Background colors
background: "#1a1a1a"
background_alt: "#2d2d2d"
# Foreground colors
foreground: "#f8f8f2"
foreground_alt: "#a8a8a2"
# Accent colors
accent: "#ff79c6"
accent_alt: "#bd93f9"
# Syntax highlighting
syntax_blue: "#8be9fd"
syntax_cyan: "#50fa7b"
syntax_green: "#50fa7b"
syntax_orange: "#ffb86c"
syntax_pink: "#ff79c6"
syntax_purple: "#bd93f9"
syntax_red: "#ff5555"
syntax_yellow: "#f1fa8c"
# Git colors
git_add: "#50fa7b"
git_delete: "#ff5555"
git_modify: "#ffb86c"
git_rename: "#8be9fd"
# Status colors
success: "#50fa7b"
warning: "#ffb86c"
error: "#ff5555"
info: "#8be9fd"
EOF
# Create Warp launcher configuration
local warp_launcher="$warp_config_dir/launcher.yaml"
cat > "$warp_launcher" << 'EOF'
# Warp Launcher Configuration
# Quick access to development tools and commands
launcher_items:
# Development tools
- name: "Git Status"
command: "git status"
description: "Check git repository status"
icon: "git"
- name: "Docker PS"
command: "docker ps"
description: "List running containers"
icon: "docker"
- name: "Kubernetes Pods"
command: "kubectl get pods"
description: "List kubernetes pods"
icon: "kubernetes"
- name: "Python REPL"
command: "python3"
description: "Start Python interactive shell"
icon: "python"
- name: "Node REPL"
command: "node"
description: "Start Node.js interactive shell"
icon: "node"
- name: "Go Playground"
command: "go run main.go"
description: "Run Go program"
icon: "go"
- name: "Rust REPL"
command: "evcxr"
description: "Start Rust REPL (if installed)"
icon: "rust"
# Project navigation
- name: "Projects"
command: "cd ~/Projects"
description: "Navigate to projects directory"
icon: "folder"
- name: "Development"
command: "cd ~/Development"
description: "Navigate to development directory"
icon: "folder"
# System tools
- name: "System Info"
command: "system_profiler SPHardwareDataType"
description: "Show system information"
icon: "info"
- name: "Network Info"
command: "ifconfig | grep 'inet ' | grep -v 127.0.0.1"
description: "Show network interfaces"
icon: "network"
EOF
# Set Warp as default terminal
print_status "Setting Warp as default terminal..."
# Create a script to set Warp as default
local set_warp_default="$HOME/set_warp_default.sh"
cat > "$set_warp_default" << 'EOF'
#!/bin/bash
# Script to set Warp as default terminal
echo "Setting Warp as default terminal..."
echo "Note: You may need to manually set this in System Preferences > General > Default web browser"
# Try to set default terminal (this may require user interaction)
if command -v warp &>/dev/null; then
# Create a simple script to launch Warp
cat > /usr/local/bin/terminal << 'EOF2'
#!/bin/bash
open -a Warp
EOF2
chmod +x /usr/local/bin/terminal
echo "Created /usr/local/bin/terminal launcher"
echo "You can now use 'terminal' command to launch Warp"
else
echo "Warp not found. Please install it first."
fi
EOF
chmod +x "$set_warp_default"
# Add Warp-specific aliases to shell configuration
cat >> "$HOME/.shell_common" << 'EOF'
# Warp terminal aliases and functions
if command -v warp &>/dev/null; then
alias w='warp'
alias wd='warp --working-directory .'
alias wp='warp --working-directory ~/Projects'
alias wdev='warp --working-directory ~/Development'
# Quick Warp launcher
warp_launch() {
local query="$1"
if [ -n "$query" ]; then
warp --launcher "$query"
else
warp --launcher
fi
}
alias wl='warp_launcher'
# Warp with specific shell
warp_shell() {
local shell="$1"
case "$shell" in
"bash"|"b")
warp --shell bash
;;
"zsh"|"z")
warp --shell zsh
;;
"fish"|"f")
warp --shell fish
;;
*)
echo "Usage: warp_shell [bash|zsh|fish]"
echo "Shortcuts: b, z, f"
;;
esac
}
alias ws='warp_shell'
fi
# AI/ML Development aliases
alias jl='jupyter lab'
alias jn='jupyter notebook'
alias mlflow='mlflow ui'
alias wandb='wandb login'
alias tf='tensorflow'
alias torch='python -c "import torch; print(f\"PyTorch {torch.__version__}\")"'
alias tf-gpu='python -c "import tensorflow as tf; print(f\"TensorFlow {tf.__version__}\"); print(f\"GPU Available: {tf.config.list_physical_devices('GPU')}\")"'
# iOS Development aliases
alias xc='xcodebuild'
alias sim='xcrun simctl'
alias pod='pod install'
alias fastlane='fastlane'
alias carthage='carthage'
alias swiftlint='swiftlint'
alias swiftformat='swiftformat'
# Quick navigation to development directories
alias ai='cd ~/AI-Projects'
alias ios='cd ~/iOS-Projects'
alias proj='cd ~/Projects'
alias dev='cd ~/Development'
# Development tool shortcuts
alias gs='git status'
alias gp='git push'
alias gl='git pull'
alias gc='git commit'
alias ga='git add'
alias gco='git checkout'
alias gcb='git checkout -b'
alias gb='git branch'
alias gd='git diff'
alias glog='git log --oneline --graph --decorate'
alias gst='git stash'
alias gstp='git stash pop'
# Docker shortcuts
alias dps='docker ps'
alias dpsa='docker ps -a'
alias di='docker images'
alias drm='docker rm'
alias drmi='docker rmi'
alias dex='docker exec -it'
alias dlogs='docker logs'
alias dc='docker-compose'
# Kubernetes shortcuts
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kl='kubectl logs'
alias ka='kubectl apply'
alias kd='kubectl delete'
alias kpf='kubectl port-forward'
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'
EOF
print_success "Warp terminal configured with development optimizations"
print_status "Run '$HOME/set_warp_default.sh' to set Warp as default terminal"
}
# =============================================================================
# FINAL SETUP & CONFIGURATION
# =============================================================================
final_setup() {
print_status "Performing final setup..."
# Reload shell configuration
if [ -f "$HOME/.zshrc" ]; then
source "$HOME/.zshrc"
fi
# Set proper permissions
chmod +x "$SCRIPT_DIR/setup.sh"
# Create a completion script
cat > "$HOME/.zsh_completion" << 'EOF'
# Custom completions
autoload -U compinit
compinit
# asdf completions
. "$HOME/.asdf/completions/asdf.bash"
# Homebrew completions
if type brew &>/dev/null; then
FPATH="$(brew --prefix)/share/zsh/site-functions:${FPATH}"
autoload -Uz compinit
compinit
fi
EOF
print_success "Final setup complete"
}
# =============================================================================
# SKIP TO SECTION FUNCTIONS
# =============================================================================
skip_to_docker_section() {
print_status "🚀 Skipping to Docker section..."
print_status "This will skip all previous installations and go directly to Docker setup"
# Check if we're in the right directory
if [ ! -f "Dockerfile" ]; then
print_status "Creating Dockerfile..."
create_dockerfile
fi
# Check Docker health and build image
print_status "Checking Docker health..."
if ! docker info &>/dev/null; then
print_error "Docker daemon is not running"
print_status "Attempting to start Docker Desktop..."
if [ -d "/Applications/Docker.app" ]; then
open -a Docker
print_status "Waiting for Docker to start..."
sleep 10
# Wait for Docker to be ready
local attempts=0
while [ $attempts -lt 30 ]; do
if docker info &>/dev/null; then
print_success "Docker daemon is now running"
break
fi
sleep 2
attempts=$((attempts + 1))
done
if [ $attempts -eq 30 ]; then
print_error "Docker daemon failed to start"
print_status "Please start Docker Desktop manually and run: ./scripts/setup_docker.sh"
exit 1
fi
else
print_error "Docker Desktop not found"
print_status "Please install Docker Desktop first"
exit 1
fi
fi
# Build Docker image
print_status "Building Docker image..."
if build_docker_image; then
print_success "🎉 Docker setup completed successfully!"
print_status "You can now use: docker run -it --rm --platform linux/arm64 custom-dev-image-arm64"
else
print_error "Docker setup failed"
print_status "Run the dedicated Docker script for troubleshooting: ./scripts/setup_docker.sh"
exit 1
fi
}
continue_after_docker_section() {
print_status "🚀 Continuing setup after Docker section..."
print_status "This will resume the setup from where the Docker section left off"
# Check if Docker image exists to confirm Docker section was completed
if ! docker images | grep -q "custom-dev-image-arm64" 2>/dev/null; then
print_warning "Docker image 'custom-dev-image-arm64' not found"
print_status "Docker section may not be complete. It's recommended to complete Docker setup first."
echo ""
read -p "Do you still want to continue? (y/N): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
print_status "Setup continuation cancelled"
exit 0
fi
else
print_success "Docker image found. Continuing with remaining setup..."
fi
# Continue with the remaining setup phases
print_status "Phase 11: Final setup and configuration..."
# Final setup
safe_execute final_setup "Final configuration setup"
# Generate final comprehensive report
generate_final_report
echo -e "${GREEN}🎉 Setup continuation completed! Your development environment is ready!${NC}"
echo -e "${BLUE}📊 Installation Summary:${NC}"
echo -e " • ✅ Successful: ${#SUCCESSFUL_INSTALLS[@]} components"
echo -e " • ❌ Failed: ${#FAILED_INSTALLS[@]} components"
echo -e " • ⏭️ Skipped: ${#SKIPPED_INSTALLS[@]} components"
echo -e " • 📋 Setup log: $SETUP_LOG"
echo -e " • 📊 System report: $SYSTEM_REPORT"
if [ ${#FAILED_INSTALLS[@]} -gt 0 ]; then
echo -e "${YELLOW}⚠️ Some installations failed. Check $ERROR_LOG for details.${NC}"
fi
echo -e "${BLUE}Next steps:${NC}"
echo -e " • Restart your terminal or run: source ~/.zshrc"
echo -e " • Check your installed tools: asdf list"
echo -e " • Explore your new development environment!"
echo -e " • Review the complete system report: $SYSTEM_REPORT"
}
# =============================================================================
# MAIN EXECUTION FUNCTION
# =============================================================================
main() {
# Initialize logging system
initialize_logging
echo -e "${BLUE}🚀 Starting enhanced setup for macOS MacBook Pro M4 Max...${NC}"
echo -e "${BLUE}================================================${NC}"
# =============================================================================
# PHASE 1: SYSTEM FOUNDATION & CORE DEPENDENCIES
# =============================================================================
log_entry "INFO" "Phase 1: Setting up system foundation..."
# Check system requirements
safe_execute check_architecture "System architecture detection"
safe_execute install_rosetta "Rosetta 2 installation"
safe_execute install_xcode_cli_tools "Xcode Command Line Tools installation"
safe_execute install_homebrew "Homebrew installation"
# Ensure Homebrew is in PATH for this session
if command -v brew >/dev/null 2>&1; then
print_success "Homebrew is available"
else
print_status "Reloading Homebrew PATH..."
eval "$(/opt/homebrew/bin/brew shellenv)"
if command -v brew >/dev/null 2>&1; then
print_success "Homebrew PATH reloaded successfully"
else
print_error "Failed to reload Homebrew PATH"
fi
fi
# Validate Homebrew packages to prevent issues
safe_execute validate_brew_packages "Homebrew package validation"
# Verify critical dependencies are available
safe_execute verify_dependencies "Critical dependency verification"
# Install core system dependencies first
safe_execute install_core_system_dependencies "Core system dependencies installation"
# Install additional tools and dependencies
safe_execute install_additional_tools "Additional tools and dependencies installation"
# =============================================================================
# PHASE 2: VERSION MANAGEMENT & LANGUAGE TOOLS
# =============================================================================
log_entry "INFO" "Phase 2: Installing version management and language tools..."
safe_execute install_asdf "ASDF version manager installation"
# Ensure ASDF is loaded in current session
if [ -f "$HOME/.asdf/asdf.sh" ]; then
print_status "Loading ASDF in current session..."
. "$HOME/.asdf/asdf.sh"
if command -v asdf >/dev/null 2>&1; then
print_success "ASDF loaded successfully in current session"
else
print_error "Failed to load ASDF in current session"
fi
fi
safe_execute install_language_plugins "Language plugin installation"
safe_execute install_language_versions "Language version installation"
# Install Python packages via ASDF Python
safe_execute install_python_packages "Python package installation via ASDF"
# =============================================================================
# PHASE 3: DEVELOPMENT ENVIRONMENT & TOOLS
# =============================================================================
log_entry "INFO" "Phase 3: Setting up development environment..."
safe_execute setup_development_environment "Development environment setup"
safe_execute setup_python_virtual_environments "Python virtual environments setup"
safe_execute setup_shell_environment "Shell environment setup"
safe_execute setup_git_configuration "Git configuration setup"
# =============================================================================
# PHASE 4: AI/ML DEVELOPMENT TOOLS
# =============================================================================
log_entry "INFO" "Phase 4: Installing AI/ML development tools..."
safe_execute install_ai_ml_dependencies "AI/ML dependencies installation"
safe_execute setup_ai_development "AI/ML development environment setup"
# =============================================================================
# PHASE 5: iOS DEVELOPMENT TOOLS
# =============================================================================
log_entry "INFO" "Phase 5: Installing iOS development tools..."
safe_execute install_ios_dependencies "iOS dependencies installation"
safe_execute setup_ios_development "iOS development environment setup"
# =============================================================================
# PHASE 6: BUILD TOOLS & PROGRAMMING LANGUAGES
# =============================================================================
log_entry "INFO" "Phase 6: Installing build tools and programming languages..."
safe_execute install_build_tools "Build tools installation"
safe_execute install_programming_languages "Programming languages installation"
# =============================================================================
# PHASE 7: WEB & CONTAINER TOOLS
# =============================================================================
log_entry "INFO" "Phase 7: Installing web and container tools..."
safe_execute install_web_development_tools "Web development tools installation"
safe_execute install_container_tools "Container tools installation"
# =============================================================================
# PHASE 8: DATABASE & INFRASTRUCTURE TOOLS
# =============================================================================
log_entry "INFO" "Phase 8: Installing database and infrastructure tools..."
safe_execute install_database_tools "Database tools installation"
safe_execute install_infrastructure_tools "Infrastructure tools installation"
# =============================================================================
# PHASE 9: NETWORKING & SECURITY TOOLS
# =============================================================================
log_entry "INFO" "Phase 9: Installing networking and security tools..."
safe_execute install_networking_tools "Networking tools installation"
safe_execute install_security_tools "Security tools installation"
# =============================================================================
# PHASE 10: EDITORS & TERMINAL TOOLS
# =============================================================================
log_entry "INFO" "Phase 10: Installing editors and terminal tools..."
safe_execute setup_vscode_extensions "VS Code extensions setup"
safe_execute setup_warp_terminal "Warp terminal setup"
# =============================================================================
# PHASE 11: FINAL SETUP & DOCKER
# =============================================================================
log_entry "INFO" "Phase 11: Final setup and Docker configuration..."
safe_execute create_dockerfile "Dockerfile creation"
safe_execute build_docker_image "Docker image building"
safe_execute final_setup "Final configuration setup"
# Generate final comprehensive report
generate_final_report
echo -e "${GREEN}🎉 Setup complete! Your MacBook Pro M4 Max is ready for development!${NC}"
echo -e "${BLUE}📊 Installation Summary:${NC}"
echo -e " • ✅ Successful: ${#SUCCESSFUL_INSTALLS[@]} components"
echo -e " • ❌ Failed: ${#FAILED_INSTALLS[@]} components"
echo -e " • ⏭️ Skipped: ${#SKIPPED_INSTALLS[@]} components"
echo -e " • 📋 Setup log: $SETUP_LOG"
echo -e " • 📊 System report: $SYSTEM_REPORT"
if [ ${#FAILED_INSTALLS[@]} -gt 0 ]; then
echo -e "${YELLOW}⚠️ Some installations failed. Check $ERROR_LOG for details.${NC}"
fi
echo -e "${BLUE}Next steps:${NC}"
echo -e " • Restart your terminal or run: source ~/.zshrc"
echo -e " • Run: docker run -it --rm --platform linux/arm64 custom-dev-image-arm64"
echo -e " • Check your installed tools: asdf list"
echo -e " • Explore your new development environment!"
echo -e " • Review the complete system report: $SYSTEM_REPORT"
echo -e "${BLUE}Python Virtual Environments:${NC}"
echo -e " • Pre-created environments: dev, web, data"
echo -e " • Use 'workon <env_name>' to activate virtualenvwrapper environments"
echo -e " • Use 'poetry new <project>' for new Poetry projects"
echo -e " • Use 'pipenv --python $(asdf where python)/bin/python' for new Pipenv projects"
echo -e " • Quick aliases: va (activate), vd (deactivate), vc (create), vr (remove)"
echo -e "${BLUE}ASDF Language Management:${NC}"
echo -e " • Core languages: Python, Node.js, Go, Rust, Ruby, Java"
echo -e " • Web languages: PHP, Elixir, Erlang, Crystal"
echo -e " • Functional: Haskell, OCaml, Clojure, Scala"
echo -e " • Systems: Nim, Zig"
echo -e " • Data Science: R, Julia"
echo -e " • Tools: Terraform, kubectl, Docker, Helm, databases"
echo -e " • Quick aliases: al (list), ac (current), apl (plugins), ai (install)"
echo -e "${BLUE}Shell Features:${NC}"
echo -e " • Universal configuration for bash, zsh, and fish"
echo -e " • Easy shell switching: 'b' (bash), 'z' (zsh), 'f' (fish)"
echo -e " • Color prompts and enhanced aliases in all shells"
echo -e " • Vi mode enabled for command line editing"
echo -e " • Enhanced completions and history management"
echo -e "${BLUE}Warp Terminal:${NC}"
echo -e " • AI-powered terminal with GPU acceleration"
echo -e " • Custom development theme and keybindings"
echo -e " • Quick launcher for development tools"
echo -e " • Aliases: w (warp), wd (current dir), wp (projects), wl (launcher)"
echo -e " • Run '$HOME/set_warp_default.sh' to set as default terminal"
echo -e "${BLUE}AI/ML Development:${NC}"
echo -e " • PyTorch with MPS support for M4 Max GPU acceleration"
echo -e " • TensorFlow with Metal support for Apple Silicon"
echo -e " • Jupyter Lab, MLflow, Weights & Biases integration"
echo -e " • Hugging Face transformers, diffusers, and datasets"
echo -e " • Streamlit, Gradio, and Panel for AI apps"
echo -e " • Project templates in ~/AI-Projects"
echo -e "${BLUE}iOS Development:${NC}"
echo -e " • Xcode Command Line Tools and iOS Simulator"
echo -e " • CocoaPods, Fastlane, and Carthage for dependency management"
echo -e " • SwiftLint, SwiftFormat for code quality"
echo -e " • iOS deployment and device management tools"
echo -e " • Project templates in ~/iOS-Projects"
}
# =============================================================================
# SCRIPT EXECUTION
# =============================================================================
# Parse command line arguments
case "${1:-}" in
"--docker"|"-d")
print_status "🐳 Docker-only mode selected"
skip_to_docker_section
exit 0
;;
"--continue-after-docker"|"-c")
print_status "🚀 Continue after Docker section mode selected"
continue_after_docker_section
exit 0
;;
"--help"|"-h")
echo "Usage: $0 [OPTION]"
echo ""
echo "Options:"
echo " --docker, -d Skip to Docker section only"
echo " --continue-after-docker, -c Continue after Docker section"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 Run full setup"
echo " $0 --docker Skip to Docker section only"
echo " $0 -d Skip to Docker section only"
echo " $0 --continue-after-docker Continue after Docker section"
echo " $0 -c Continue after Docker section"
echo ""
echo "For Docker-only setup with error handling, use: ./scripts/setup_docker.sh"
exit 0
;;
"")
# No arguments, run full setup
;;
*)
print_error "Unknown option: $1"
print_status "Use --help for usage information"
exit 1
;;
esac
# Run main function
main "$@"
# =============================================================================
# SETUP COMPLETE
# =============================================================================
#
# Your macOS MacBook Pro M4 Max is now configured with:
#
# ✅ Complete development environment
# ✅ AI/ML tools with GPU acceleration
# ✅ iOS development toolchain
# ✅ Modern terminal (Warp) with AI features
# ✅ Universal shell configuration
# ✅ 100+ development aliases and shortcuts
# ✅ Project templates and directory structure
# ✅ Performance optimizations for Apple Silicon
#
# =============================================================================
# INSTALLATION SEQUENCE SUMMARY
# =============================================================================
#
# Phase 1: System Foundation & Core Dependencies
# Phase 2: Version Management & Language Tools
# Phase 3: Development Environment & Tools
# Phase 4: AI/ML Development Tools
# Phase 5: iOS Development Tools
# Phase 6: Build Tools & Programming Languages
# Phase 7: Web & Container Tools
# Phase 8: Database & Infrastructure Tools
# Phase 9: Networking & Security Tools
# Phase 10: Editors & Terminal Tools
# Phase 11: Final Setup & Docker
#
# =============================================================================
# DEPENDENCY ORDERING
# =============================================================================
#
# ✅ Core system tools installed first (git, curl, openssl, etc.)
# ✅ Development utilities installed second (jq, yq, htop, etc.)
# ✅ Shell enhancements installed third (zsh tools, fish, etc.)
# ✅ Language tools installed fourth (asdf, Python, Node.js, etc.)
# ✅ AI/ML libraries installed fifth (PyTorch, TensorFlow, etc.)
# ✅ Build tools installed sixth (cmake, ninja, bazel, etc.)
# ✅ Web tools installed seventh (Node.js, Yarn, etc.)
# ✅ Container tools installed eighth (Docker, Kubernetes, etc.)
# ✅ Database tools installed ninth (PostgreSQL, Redis, etc.)
# ✅ Infrastructure tools installed tenth (Terraform, Helm, etc.)
# ✅ Networking tools installed eleventh (nmap, Wireshark, etc.)
# ✅ Security tools installed twelfth (GPG, SSH tools, etc.)
# ✅ Terminal tools installed last (Warp, VS Code, etc.)
#
# =============================================================================
# NEW FEATURES ADDED
# =============================================================================
#
# 🛡️ ERROR RECOVERY & RESILIENCE
# - Automatic retry mechanism (3 attempts per component)
# - Graceful failure handling with user choice to continue
# - Component isolation to prevent cascade failures
# - Detailed error logging and tracking
#
# 📋 COMPREHENSIVE LOGGING
# - Real-time installation progress tracking
# - Detailed success/failure/skip status for each component
# - Timestamped log entries with categorization
# - Separate error log for troubleshooting
# - Markdown-formatted logs for easy reading
#
# 📊 SYSTEM REPORTING
# - Complete installation summary with statistics
# - Comprehensive usage instructions for all tools
# - Update and uninstall procedures
# - Troubleshooting guides and common solutions
# - Configuration file locations and management
#
# 📁 LOG FILES CREATED
# - SETUP.LOG.md: Complete installation progress log
# - SETUP_ERRORS.log: Detailed error information
# - SYSTEM.REPORT.md: Comprehensive system documentation
#
# Next steps:
# 1. Restart your terminal or run: source ~/.zshrc
# 2. Explore your new environment: ai, ios, proj, dev
# 3. Start developing with: jl, warp, or your preferred tools
# 4. Review your system report: ~/SYSTEM.REPORT.md
# 5. Check setup logs if you encounter issues: ~/SETUP.LOG.md
#
# Happy coding! 🚀
# =============================================================================
#!/usr/bin/env bash
# =============================================================================
# Quick Setup Launcher
# =============================================================================
#
# This script provides quick access to different setup options
# without having to remember command line arguments
#
# Usage: ./scripts/quick_setup.sh
#
# =============================================================================
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
print_status() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
show_menu() {
clear
echo -e "${BLUE}🚀 Quick Setup Launcher${NC}"
echo -e "${BLUE}======================${NC}"
echo ""
echo -e "${CYAN}Choose your setup option:${NC}"
echo ""
echo -e " ${GREEN}1)${NC} Full Development Environment Setup"
echo -e " Complete setup with all tools and languages"
echo ""
echo -e " ${GREEN}2)${NC} Docker Setup Only"
echo -e " Skip to Docker configuration and image building"
echo ""
echo -e " ${GREEN}3)${NC} Docker Setup with Error Recovery"
echo -e " Dedicated Docker script with troubleshooting"
echo ""
echo -e " ${GREEN}4)${NC} Continue After Docker Section"
echo -e " Resume setup from where Docker left off"
echo ""
echo -e " ${GREEN}5)${NC} Check System Status"
echo -e " Verify what's already installed"
echo ""
echo -e " ${GREEN}6)${NC} Help & Information"
echo -e " Show usage and troubleshooting info"
echo ""
echo -e " ${GREEN}0)${NC} Exit"
echo ""
echo -e "${YELLOW}Enter your choice (0-6):${NC} "
}
check_system_status() {
print_status "Checking system status..."
echo ""
# Check Homebrew
if command -v brew &>/dev/null; then
print_success "✓ Homebrew: $(brew --version | head -1)"
else
print_error "✗ Homebrew: Not installed"
fi
# Check ASDF
if command -v asdf &>/dev/null; then
print_success "✓ ASDF: $(asdf --version)"
else
print_error "✗ ASDF: Not installed"
fi
# Check Docker
if command -v docker &>/dev/null; then
if docker info &>/dev/null; then
print_success "✓ Docker: $(docker --version) (Running)"
else
print_warning "⚠ Docker: $(docker --version) (Not running)"
fi
else
print_error "✗ Docker: Not installed"
fi
# Check Python
if command -v python3 &>/dev/null; then
print_success "✓ Python: $(python3 --version)"
else
print_error "✗ Python: Not installed"
fi
# Check Node.js
if command -v node &>/dev/null; then
print_success "✓ Node.js: $(node --version)"
else
print_error "✗ Node.js: Not installed"
fi
# Check Go
if command -v go &>/dev/null; then
print_success "✓ Go: $(go version)"
else
print_error "✗ Go: Not installed"
fi
echo ""
print_status "System status check complete"
}
show_help() {
clear
echo -e "${BLUE}📚 Setup Help & Information${NC}"
echo -e "${BLUE}============================${NC}"
echo ""
echo -e "${CYAN}Available Setup Options:${NC}"
echo ""
echo -e "${GREEN}1. Full Setup${NC}"
echo -e " ./scripts/setup.sh"
echo -e " Complete development environment installation"
echo ""
echo -e "${GREEN}2. Docker Only${NC}"
echo -e " ./scripts/setup.sh --docker"
echo -e " Skip to Docker section"
echo ""
echo -e "${GREEN}3. Docker with Recovery${NC}"
echo -e " ./scripts/setup_docker.sh"
echo -e " Dedicated Docker script with error handling"
echo ""
echo -e "${GREEN}4. Continue After Docker${NC}"
echo -e " ./scripts/setup.sh --continue-after-docker"
echo -e " Resume setup from where Docker left off"
echo ""
echo ""
echo -e "${CYAN}Troubleshooting:${NC}"
echo ""
echo -e "• If Docker fails to start:"
echo -e " - Check if Docker Desktop is installed"
echo -e " - Launch Docker Desktop manually"
echo -e " - Run: ./scripts/setup_docker.sh"
echo ""
echo -e "• If setup fails:"
echo -e " - Check logs in ~/SETUP.LOG.md"
echo -e " - Check errors in ~/SETUP_ERRORS.log"
echo -e " - Run specific sections as needed"
echo ""
echo -e "• Common issues:"
echo -e " - Docker daemon not running"
echo -e " - Insufficient disk space"
echo -e " - Network connectivity issues"
echo ""
echo -e "${CYAN}Support:${NC}"
echo -e "• Check the generated system report: ~/SYSTEM.REPORT.md"
echo -e "• Review setup logs for detailed information"
echo -e "• Use the dedicated Docker script for Docker-specific issues"
}
run_full_setup() {
print_status "Starting full development environment setup..."
echo ""
print_status "This will install all development tools and languages."
print_status "This process may take 30-60 minutes depending on your system."
echo ""
read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Starting full setup..."
cd "$SCRIPT_DIR"
./setup.sh
else
print_status "Full setup cancelled"
fi
}
run_docker_setup() {
print_status "Starting Docker-only setup..."
echo ""
print_status "This will skip to Docker configuration and build the ARM64 image."
print_status "This process may take 10-20 minutes."
echo ""
read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Starting Docker setup..."
cd "$SCRIPT_DIR"
./setup.sh --docker
else
print_status "Docker setup cancelled"
fi
}
run_docker_recovery() {
print_status "Starting Docker setup with error recovery..."
echo ""
print_status "This will run the dedicated Docker script with troubleshooting."
print_status "This is recommended if you're having Docker issues."
echo ""
read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Starting Docker recovery setup..."
cd "$SCRIPT_DIR"
./setup_docker.sh
else
print_status "Docker recovery setup cancelled"
fi
}
continue_after_docker() {
print_status "Continuing setup after Docker section..."
echo ""
print_status "This will resume the setup from where the Docker section left off."
print_status "This includes final configuration, VS Code extensions, Warp terminal setup,"
print_status "and other remaining components."
echo ""
print_status "This process may take 10-20 minutes depending on what's already installed."
echo ""
read -p "Do you want to continue? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Continuing setup after Docker section..."
cd "$SCRIPT_DIR"
# Check if Docker image exists to confirm Docker section was completed
if docker images | grep -q "custom-dev-image-arm64" 2>/dev/null; then
print_success "Docker image found. Continuing with remaining setup..."
# Run the main setup script with a flag to continue after Docker
# We'll need to modify the main script to support this
print_status "Running remaining setup components..."
./setup.sh --continue-after-docker
else
print_warning "Docker image not found. Docker section may not be complete."
print_status "It's recommended to complete Docker setup first."
echo ""
read -p "Do you still want to continue? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
print_status "Continuing with remaining setup..."
./setup.sh --continue-after-docker
else
print_status "Setup continuation cancelled"
fi
fi
else
print_status "Setup continuation cancelled"
fi
}
main() {
while true; do
show_menu
read -r choice
case $choice in
1)
run_full_setup
;;
2)
run_docker_setup
;;
3)
run_docker_recovery
;;
4)
continue_after_docker
;;
5)
check_system_status
echo ""
read -p "Press Enter to continue..."
;;
6)
show_help
echo ""
read -p "Press Enter to continue..."
;;
0)
print_status "Exiting..."
exit 0
;;
*)
print_error "Invalid choice. Please enter a number between 0 and 6."
sleep 2
;;
esac
echo ""
read -p "Press Enter to return to menu..."
done
}
# Run main function
main "$@"
#!/usr/bin/env bash
# =============================================================================
# Docker Setup Sub Script - Skip to Docker Section
# =============================================================================
#
# This script skips the main setup and goes directly to Docker configuration
# It handles Docker daemon errors and provides recovery options
#
# Usage: ./scripts/setup_docker.sh
#
# =============================================================================
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
print_status() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
print_skip() {
echo -e "${PURPLE}[SKIP]${NC} $1"
}
# =============================================================================
# DOCKER DAEMON CHECK & RECOVERY
# =============================================================================
check_docker_daemon() {
print_status "Checking Docker daemon status..."
if docker info &>/dev/null; then
print_success "Docker daemon is running"
return 0
else
print_error "Docker daemon is not running"
return 1
fi
}
start_docker_daemon() {
print_status "Attempting to start Docker daemon..."
# Check if Docker Desktop is installed
if [ -d "/Applications/Docker.app" ]; then
print_status "Docker Desktop found, starting it..."
open -a Docker
# Wait for Docker to start
print_status "Waiting for Docker to start (this may take a minute)..."
local attempts=0
local max_attempts=60
while [ $attempts -lt $max_attempts ]; do
if docker info &>/dev/null; then
print_success "Docker daemon started successfully"
return 0
fi
sleep 2
attempts=$((attempts + 1))
print_status "Waiting for Docker... (attempt $attempts/$max_attempts)"
done
print_error "Docker daemon failed to start after $max_attempts attempts"
return 1
else
print_error "Docker Desktop not found in Applications folder"
return 1
fi
}
install_docker_desktop() {
print_status "Docker Desktop not found. Installing via Homebrew..."
if command -v brew &>/dev/null; then
if brew install --cask docker; then
print_success "Docker Desktop installed successfully"
print_status "Please launch Docker Desktop manually and then run this script again"
return 0
else
print_error "Failed to install Docker Desktop via Homebrew"
return 1
fi
else
print_error "Homebrew not found. Please install Homebrew first or download Docker Desktop manually from https://www.docker.com/products/docker-desktop/"
return 1
fi
}
# =============================================================================
# DOCKER CONFIGURATION FUNCTIONS
# =============================================================================
create_dockerfile() {
print_status "Creating optimized Dockerfile for ARM64..."
cat > Dockerfile << 'EOF'
# Multi-stage build for ARM64
FROM --platform=linux/arm64 alpine:latest AS base
# Install system dependencies
RUN apk update && apk add --no-cache \
bash \
curl \
git \
build-base \
openssl-dev \
zlib-dev \
readline-dev \
libffi-dev \
pkgconfig \
cmake \
ninja \
llvm \
&& rm -rf /var/cache/apk/*
# Install Python
RUN apk add --no-cache python3 py3-pip \
&& python3 -m ensurepip --upgrade \
&& pip3 install --no-cache --upgrade pip --break-system-packages
# Install Node.js
RUN apk add --no-cache nodejs npm
# Install Go
RUN apk add --no-cache go
# Install Rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
# Set working directory
WORKDIR /workspace
# Default command
CMD ["/bin/bash"]
EOF
print_success "Dockerfile created for ARM64"
}
build_docker_image() {
print_status "Building Docker image for ARM64..."
# Check if Dockerfile exists
if [ ! -f "Dockerfile" ]; then
print_error "Dockerfile not found. Creating it first..."
create_dockerfile
fi
# Check Docker daemon status before building
if ! check_docker_daemon; then
print_error "Cannot build Docker image: Docker daemon is not running"
print_status "Attempting to start Docker daemon..."
if ! start_docker_daemon; then
print_error "Failed to start Docker daemon. Please start Docker Desktop manually and try again."
return 1
fi
fi
# Build the image with error handling
if docker build --platform linux/arm64 -t custom-dev-image-arm64 . 2>&1; then
print_success "Docker image built successfully for ARM64"
return 0
else
print_error "Failed to build Docker image"
# Check for specific Docker errors
if docker info &>/dev/null; then
print_status "Docker daemon is running, but build failed. Checking for common issues..."
# Check available disk space
local available_space=$(df -h . | awk 'NR==2 {print $4}' | sed 's/[^0-9]//g')
if [ "$available_space" -lt 10 ]; then
print_warning "Low disk space available: ${available_space}GB. Docker build requires at least 10GB free space."
fi
# Check Docker buildx
if ! docker buildx version &>/dev/null; then
print_warning "Docker buildx not available. Installing buildx component..."
docker buildx install
fi
# Try building with buildx
print_status "Retrying build with buildx..."
if docker buildx build --platform linux/arm64 -t custom-dev-image-arm64 . --load; then
print_success "Docker image built successfully using buildx"
return 0
else
print_error "Build failed even with buildx"
return 1
fi
else
print_error "Docker daemon is not accessible"
return 1
fi
fi
}
run_docker_container() {
print_status "Running Docker container..."
# Check if image exists
if ! docker images | grep -q "custom-dev-image-arm64"; then
print_error "Docker image 'custom-dev-image-arm64' not found. Please build it first."
return 1
fi
# Check Docker daemon status
if ! check_docker_daemon; then
print_error "Cannot run Docker container: Docker daemon is not running"
return 1
fi
if docker run -it --rm --platform linux/arm64 custom-dev-image-arm64 /bin/bash; then
print_success "Docker container completed successfully"
return 0
else
print_warning "Docker container exited"
return 1
fi
}
# =============================================================================
# DOCKER HEALTH CHECK
# =============================================================================
check_docker_health() {
print_status "Performing Docker health check..."
local health_status=0
# Check Docker daemon
if check_docker_daemon; then
print_success "✓ Docker daemon is running"
else
print_error "✗ Docker daemon is not running"
health_status=1
fi
# Check Docker version
if docker --version &>/dev/null; then
local docker_version=$(docker --version)
print_success "✓ Docker version: $docker_version"
else
print_error "✗ Docker version check failed"
health_status=1
fi
# Check Docker info
if docker info &>/dev/null; then
print_success "✓ Docker info accessible"
else
print_error "✗ Docker info not accessible"
health_status=1
fi
# Check buildx
if docker buildx version &>/dev/null; then
print_success "✓ Docker buildx available"
else
print_warning "⚠ Docker buildx not available (legacy builder will be used)"
fi
# Check available images
local image_count=$(docker images -q | wc -l)
print_status "✓ Available Docker images: $image_count"
# Check available containers
local container_count=$(docker ps -aq | wc -l)
print_status "✓ Available Docker containers: $container_count"
return $health_status
}
# =============================================================================
# DOCKER TROUBLESHOOTING
# =============================================================================
troubleshoot_docker() {
print_status "Running Docker troubleshooting..."
print_status "1. Checking Docker Desktop status..."
if pgrep -f "Docker Desktop" >/dev/null; then
print_success "Docker Desktop process is running"
else
print_warning "Docker Desktop process not found"
fi
print_status "2. Checking Docker socket..."
if [ -S "/var/run/docker.sock" ]; then
print_success "Docker socket exists"
ls -la /var/run/docker.sock
else
print_error "Docker socket not found"
fi
print_status "3. Checking Docker group membership..."
if groups $USER | grep -q docker; then
print_success "User is in docker group"
else
print_warning "User is not in docker group"
print_status "You may need to add your user to the docker group or restart Docker Desktop"
fi
print_status "4. Checking Docker Desktop logs..."
if [ -f "$HOME/Library/Containers/com.docker.docker/Data/log/vm/dockerd.log" ]; then
print_status "Recent Docker daemon logs:"
tail -10 "$HOME/Library/Containers/com.docker.docker/Data/log/vm/dockerd.log" 2>/dev/null || print_warning "Cannot read Docker logs"
else
print_warning "Docker logs not found"
fi
print_status "5. Checking system resources..."
print_status "Available disk space:"
df -h . | head -2
print_status "Available memory:"
vm_stat | head -5
}
# =============================================================================
# MAIN EXECUTION
# =============================================================================
main() {
echo -e "${BLUE}🐳 Docker Setup Script - Skip to Docker Section${NC}"
echo -e "${BLUE}==============================================${NC}"
# Check if we're in the right directory
if [ ! -f "$SCRIPT_DIR/setup.sh" ]; then
print_error "This script must be run from the scripts directory or with the main setup script present"
exit 1
fi
# Phase 1: Docker Health Check
print_status "Phase 1: Checking Docker health..."
if ! check_docker_health; then
print_warning "Docker health check failed. Attempting to fix..."
if ! start_docker_daemon; then
print_error "Failed to start Docker daemon automatically"
print_status "Attempting to install Docker Desktop..."
if ! install_docker_desktop; then
print_error "Failed to install Docker Desktop"
print_status "Please install Docker Desktop manually from https://www.docker.com/products/docker-desktop/"
print_status "Then run this script again"
exit 1
fi
fi
# Wait a bit and check again
sleep 5
if ! check_docker_health; then
print_error "Docker is still not healthy after recovery attempts"
troubleshoot_docker
exit 1
fi
fi
# Phase 2: Docker Configuration
print_status "Phase 2: Setting up Docker configuration..."
safe_execute create_dockerfile "Dockerfile creation"
# Phase 3: Docker Image Building
print_status "Phase 3: Building Docker image..."
if safe_execute build_docker_image "Docker image building"; then
print_success "Docker image built successfully!"
# Phase 4: Test Docker Container
print_status "Phase 4: Testing Docker container..."
safe_execute run_docker_container "Docker container test"
print_success "🎉 Docker setup completed successfully!"
print_status "You can now use: docker run -it --rm --platform linux/arm64 custom-dev-image-arm64"
else
print_error "❌ Docker setup failed"
troubleshoot_docker
exit 1
fi
}
# Safe execute function (copied from main script)
safe_execute() {
local function_name="$1"
local description="$2"
local max_retries="${3:-3}"
local retry_count=0
print_status "🔄 Executing: $description"
while [ $retry_count -lt $max_retries ]; do
if "$function_name"; then
print_success "$description completed successfully"
return 0
else
retry_count=$((retry_count + 1))
if [ $retry_count -lt $max_retries ]; then
print_warning "⚠️ $description failed (attempt $retry_count/$max_retries), retrying..."
sleep 2
else
print_error "$description failed after $max_retries attempts"
return 1
fi
fi
done
}
# Run main function
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment