#!/bin/bash

# =============================================================================
# Ubuntu 24.04.2 LTS Coding Workstation Setup Script
# PURPOSE: Install VS Code, Git, Docker, GitHub CLI, FileZilla, FFmpeg, Pandoc, AI tools (Codex, Claude Code, Grok, Gemini)
# LAST UPDATED: January 24, 2026
# KEY ENHANCEMENT: Updated Claude Code to use native installer (npm deprecated)
# SERVICES: Local development environment with cloud-ready tools
#
# QUICK INSTALL:
# wget -qO- https://parks.tips/scripts/linux/setup-dev-workstation.sh | bash
#
# MANUAL INSTALL:
# wget https://parks.tips/scripts/linux/setup-dev-workstation.sh
# chmod +x setup-dev-workstation.sh
# ./setup-dev-workstation.sh
# =============================================================================

set -e  # Exit on any error

# Define next steps at the top
NEXT_STEPS="=== NEXT STEPS ===
1. Log out and back in for Docker group changes to take effect
2. Configure Git and GitHub CLI:
   git config --global user.name \"Your Name\"
   git config --global user.email \"your.email@example.com\"
   gh auth login
3. Configure AWS CLI: aws configure
4. Set up Claude Code authentication: claude
   Claude Code updates automatically. To check installation health, use: claude doctor
5. Set up Gemini CLI authentication: gemini
6. Set up OpenAI Codex CLI authentication: codex login (sign in with ChatGPT)
7. Set up Grok API key:
   a. Get your API key from https://x.ai/api (sign in/create account)
   b. Add to ~/.bashrc: export GROK_API_KEY="your_api_key_here"
   c. Reload shell: source ~/.bashrc
8. Launch VS Code to complete extension installation: code
9. Pin Chrome and VS Code to dash: Search for them in Activities, right-click, 'Pin to Dash'
10. Restart your system to ensure all changes take effect
11. If setting up Thunderbird email, consider using this signature: Sent from Ubuntu 24.04.2 LTS

=== INSTALLATION LOG ===
"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Create log file on desktop
LOG_FILE="$HOME/Desktop/NEXT_STEPS.txt"
echo "$NEXT_STEPS" > "$LOG_FILE"

# Enhanced logging function that writes to both screen and file
log() {
    local message="[$(date +'%Y-%m-%d %H:%M:%S')] $1"
    echo -e "${GREEN}${message}${NC}"
    echo "$message" >> "$LOG_FILE"
}

warn() {
    local message="[WARNING] $1"
    echo -e "${YELLOW}${message}${NC}"
    echo "$message" >> "$LOG_FILE"
}

error() {
    local message="[ERROR] $1"
    echo -e "${RED}${message}${NC}"
    echo "$message" >> "$LOG_FILE"
    exit 1
}

# Log command results to file
log_command() {
    local command="$1"
    local description="$2"
    echo "COMMAND: $command" >> "$LOG_FILE"
    echo "DESCRIPTION: $description" >> "$LOG_FILE"
    if eval "$command" >> "$LOG_FILE" 2>&1; then
        echo "RESULT: SUCCESS" >> "$LOG_FILE"
        log "$description - SUCCESS"
    else
        echo "RESULT: FAILED" >> "$LOG_FILE"
        warn "$description - FAILED"
    fi
    echo "----------------------------------------" >> "$LOG_FILE"
}

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   error "This script should not be run as root. Run as your regular user."
fi

log "Starting Ubuntu 24.04.2 LTS Coding Workstation Setup..."
log "This will install: Chrome, VS Code, Git, Docker, GitHub CLI, FileZilla, FFmpeg, Pandoc, Python packages, AI tools (Claude, Codex, Gemini, Grok), and more"
echo
echo -e "${YELLOW}NOTE: If you see the warning 'The computer needs to restart to finish installing updates'${NC}"
echo -e "${YELLOW}during this installation, please ignore it until the script completes.${NC}"
echo -e "${YELLOW}You'll be prompted to restart at the end as part of the next steps.${NC}"
echo

# Update system packages
log "Updating system packages..."
sudo apt update && sudo apt upgrade -y

# Install essential dependencies
log "Installing essential dependencies..."
sudo apt install -y \
    curl \
    wget \
    gnupg \
    lsb-release \
    software-properties-common \
    apt-transport-https \
    ca-certificates \
    build-essential \
    unzip

# =============================================================================
# GIT INSTALLATION
# =============================================================================
log "Installing Git..."
sudo apt install -y git

# Configure Git (user will need to set their own credentials)
log "Git installed. You'll need to configure it with:"
echo -e "${BLUE}  git config --global user.name \"Your Name\"${NC}"
echo -e "${BLUE}  git config --global user.email \"your.email@example.com\"${NC}"

# =============================================================================
# GOOGLE CHROME INSTALLATION
# =============================================================================
log "Installing Google Chrome..."

# Download and install Google Chrome signing key
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'

# Update package cache and install Chrome
sudo apt update
sudo apt install -y google-chrome-stable

# Set Chrome as the default browser
log "Setting Chrome as the default browser..."
xdg-settings set default-web-browser google-chrome.desktop
if [ $? -eq 0 ]; then
    log "Chrome set as default browser successfully"
else
    warn "Failed to set Chrome as default browser - you can set this manually in Settings > Default Applications"
fi

# =============================================================================
# VS CODE INSTALLATION
# =============================================================================
log "Installing Visual Studio Code..."

# Download and install Microsoft GPG key
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
sudo sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list'

# Update package cache and install
sudo apt update
sudo apt install -y code

# Create VS Code user directory and basic settings to help with extension installation
log "Preparing VS Code for extension installation..."
mkdir -p ~/.config/Code/User
cat << 'EOF' > ~/.config/Code/User/settings.json
{
    "telemetry.telemetryLevel": "off",
    "update.mode": "manual",
    "extensions.autoUpdate": false
}
EOF

# Give VS Code a moment to recognize the new configuration
log "Allowing VS Code to initialize (waiting 5 seconds)..."
sleep 5

# Install useful VS Code extensions
log "Installing recommended VS Code extensions..."
log "Extensions may take a moment to install..."

# Install extensions with error handling
install_extension() {
    local extension=$1
    log "Installing extension: $extension"
    if code --install-extension "$extension" >> "$LOG_FILE" 2>&1; then
        echo "Extension $extension: SUCCESS" >> "$LOG_FILE"
        log "Extension $extension installed successfully"
    else
        echo "Extension $extension: FAILED" >> "$LOG_FILE"
        warn "Failed to install extension: $extension (you can install this manually later)"
    fi
    echo "----------------------------------------" >> "$LOG_FILE"
}

install_extension "ms-python.python"
install_extension "redhat.vscode-yaml"
install_extension "ms-vscode.vscode-typescript-next"
install_extension "ms-azuretools.vscode-docker"
install_extension "amazonwebservices.aws-toolkit-vscode"
install_extension "hashicorp.terraform"
install_extension "ms-vscode.powershell"

# =============================================================================
# DOCKER INSTALLATION
# =============================================================================
log "Installing Docker..."

# Remove any old Docker installations
for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do
    sudo apt-get remove -y $pkg 2>/dev/null || true
done

# Add Docker's official GPG key
sudo apt-get update
sudo apt-get install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add Docker repository
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker Engine
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Add current user to docker group
sudo usermod -aG docker $USER

log "Docker installed. You'll need to log out and back in for group changes to take effect."

# =============================================================================
# ADDITIONAL DEVELOPMENT TOOLS
# =============================================================================
log "Installing additional development tools..."

# Node.js (via NodeSource repository for latest LTS)
log "Installing Node.js LTS..."
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

# Configure npm to use user directory for global packages (avoid sudo requirement)
log "Configuring npm for user-level global packages..."
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'

# Add npm global directory to PATH in bashrc if not already present
if ! grep -q ".npm-global" ~/.bashrc; then
    echo '' >> ~/.bashrc
    echo '# npm global packages directory (avoids need for sudo)' >> ~/.bashrc
    echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
    log "Added ~/.npm-global/bin to PATH in ~/.bashrc"
else
    log "npm global directory already in ~/.bashrc"
fi

# Also add to current session for immediate use
export PATH=~/.npm-global/bin:$PATH

# Python development tools
sudo apt install -y python3-pip python3-venv python3-dev

# Python AWS and development packages
log "Installing Python AWS development packages..."
# Ubuntu 24.04 requires --break-system-packages for user installations (PEP 668)
pip3 install --user --upgrade pip --break-system-packages
pip3 install --user boto3 --break-system-packages      # AWS SDK for Python
pip3 install --user pytest --break-system-packages     # Testing framework
pip3 install --user requests --break-system-packages   # HTTP library
pip3 install --user black --break-system-packages      # Code formatter
pip3 install --user pylint --break-system-packages     # Code linter
pip3 install --user awscli-local --break-system-packages  # LocalStack AWS CLI

# Add Python user packages to PATH if not already present
if ! grep -q ".local/bin" ~/.bashrc; then
    echo '' >> ~/.bashrc
    echo '# Python user packages directory' >> ~/.bashrc
    echo 'export PATH=~/.local/bin:$PATH' >> ~/.bashrc
    log "Added ~/.local/bin to PATH in ~/.bashrc"
else
    log "Python user packages directory already in ~/.bashrc"
fi

# Also add to current session for immediate use
export PATH=~/.local/bin:$PATH

# Ripgrep (fast text search tool)
log "Installing ripgrep..."
sudo apt install -y ripgrep

# Pwgen (password generator)
log "Installing pwgen..."
sudo apt install -y pwgen

# FFmpeg (multimedia framework for audio/video processing)
log "Installing ffmpeg..."
sudo apt-get install -y ffmpeg

# FileZilla (FTP/SFTP client)
log "Installing FileZilla..."
sudo apt install -y filezilla

# AWS CLI v2
log "Installing AWS CLI v2..."
cd /tmp
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
rm -rf aws awscliv2.zip

# Terraform (for Infrastructure as Code)
log "Installing Terraform..."
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install -y terraform

# GitHub CLI (for repository management and CI/CD integration)
log "Installing GitHub CLI..."
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update && sudo apt install -y gh

# =============================================================================
# PANDOC AND PDF GENERATION TOOLS
# =============================================================================
log "Installing Pandoc and PDF generation engines..."

# Install core LaTeX packages for pdflatex (default pandoc PDF engine)
log "Installing LaTeX packages for PDF generation..."
sudo apt-get install -y texlive-latex-base texlive-fonts-recommended texlive-latex-extra

# Install XeLaTeX for better Unicode and font handling
log "Installing XeLaTeX..."
sudo apt-get install -y texlive-xetex

# Install wkhtmltopdf as alternative HTML-to-PDF converter
log "Installing wkhtmltopdf..."
sudo apt-get install -y wkhtmltopdf

# Install Pandoc itself
log "Installing Pandoc..."
sudo apt-get install -y pandoc

log "Pandoc and PDF tools installed successfully!"
log "You can now convert documents with commands like:"
log "  pandoc README.md -o output.pdf"
log "  pandoc README.md -o output.pdf --pdf-engine=xelatex"
log "  pandoc README.md -o output.pdf --pdf-engine=wkhtmltopdf"

# =============================================================================
# OPENAI CODEX CLI INSTALLATION
# =============================================================================
log "Installing OpenAI Codex CLI..."

# Install OpenAI Codex CLI via npm
log "Installing OpenAI Codex CLI via npm..."
if npm install -g @openai/codex >> "$LOG_FILE" 2>&1; then
    echo "OpenAI Codex CLI installation: SUCCESS" >> "$LOG_FILE"
    log "OpenAI Codex CLI installed successfully!"
    log "You can now use 'codex' command in your terminal"
else
    echo "OpenAI Codex CLI installation: FAILED" >> "$LOG_FILE"
    warn "Failed to install OpenAI Codex CLI via npm. You can try installing manually later with:"
    warn "npm install -g @openai/codex"
fi
echo "----------------------------------------" >> "$LOG_FILE"

# =============================================================================
# CLAUDE CODE INSTALLATION
# =============================================================================
log "Installing Claude Code..."

# Install Claude Code via native installer (recommended method as of 2026)
# NPM installation is deprecated in favor of the native installer
log "Installing Claude Code via native installer..."
if curl -fsSL https://claude.ai/install.sh | bash >> "$LOG_FILE" 2>&1; then
    echo "Claude Code installation: SUCCESS" >> "$LOG_FILE"
    log "Claude Code installed successfully!"
    log "You can now use 'claude' command in your terminal"
else
    echo "Claude Code installation: FAILED" >> "$LOG_FILE"
    warn "Failed to install Claude Code via native installer. You can try installing manually later with:"
    warn "curl -fsSL https://claude.ai/install.sh | bash"
fi
echo "----------------------------------------" >> "$LOG_FILE"

# =============================================================================
# VERIFY NPM GLOBAL PACKAGES PATH
# =============================================================================
log "Verifying npm global packages are accessible in PATH..."

# The npm global path should already be configured from earlier in the script
# Just verify it's working
NPM_PREFIX="$(npm config get prefix)"
log "npm global prefix is set to: $NPM_PREFIX"

# Verify Claude Code is now accessible
if command -v claude >/dev/null 2>&1; then
    log "Claude Code is now accessible: $(claude --version 2>/dev/null || echo 'Available')"
else
    warn "Claude Code still not accessible - user may need to restart terminal"
fi

# =============================================================================
# GEMINI CLI INSTALLATION
# =============================================================================
log "Installing Gemini CLI..."

# Install Gemini CLI via npm
log "Installing Gemini CLI via npm..."
if npm install -g @google/gemini-cli >> "$LOG_FILE" 2>&1; then
    echo "Gemini CLI installation: SUCCESS" >> "$LOG_FILE"
    log "Gemini CLI installed successfully!"
    
    # Ensure executable permissions
    if [ -f /usr/bin/gemini ]; then
        sudo chmod +x /usr/bin/gemini
        log "Set executable permissions for Gemini CLI"
    fi
    
    log "You can now use 'gemini' command in your terminal"
else
    echo "Gemini CLI installation: FAILED" >> "$LOG_FILE"
    warn "Failed to install Gemini CLI via npm. You can try installing manually later with:"
    warn "npm install -g @google/gemini-cli"
    warn "sudo chmod +x /usr/bin/gemini"
fi
echo "----------------------------------------" >> "$LOG_FILE"

# =============================================================================
# GROK CLI INSTALLATION
# =============================================================================
log "Installing Grok CLI..."

# Install Grok CLI via npm
log "Installing Grok CLI via npm..."
if npm install -g @vibe-kit/grok-cli >> "$LOG_FILE" 2>&1; then
    echo "Grok CLI installation: SUCCESS" >> "$LOG_FILE"
    log "Grok CLI installed successfully!"
    log "You can now use 'grok' command in your terminal"
    log "Remember to set up your API key from https://x.ai/api"
else
    echo "Grok CLI installation: FAILED" >> "$LOG_FILE"
    warn "Failed to install Grok CLI via npm. You can try installing manually later with:"
    warn "npm install -g @vibe-kit/grok-cli"
fi
echo "----------------------------------------" >> "$LOG_FILE"

# =============================================================================
# SYSTEM CONFIGURATION
# =============================================================================
log "Configuring system settings..."

# Increase inotify limits for VS Code file watching
echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.conf

# Enable Docker service
sudo systemctl enable docker
sudo systemctl start docker

# =============================================================================
# COMPLETION SUMMARY
# =============================================================================
log "Installation completed successfully!"
echo
echo -e "${GREEN}=== INSTALLATION SUMMARY ===${NC}"
echo -e "${BLUE}✓ Chrome:${NC} $(google-chrome --version)"
echo -e "${BLUE}✓ Git:${NC} $(git --version)"
echo -e "${BLUE}✓ VS Code:${NC} $(code --version | head -n1)"
echo -e "${BLUE}✓ Docker:${NC} $(docker --version)"
echo -e "${BLUE}✓ Node.js:${NC} $(node --version)"
echo -e "${BLUE}✓ Python:${NC} $(python3 --version)"
echo -e "${BLUE}✓ boto3:${NC} $(python3 -c 'import boto3; print(boto3.__version__)' 2>/dev/null || echo 'Installed')"
echo -e "${BLUE}✓ pytest:${NC} $(pytest --version 2>/dev/null | head -n1 || echo 'Installed')"
echo -e "${BLUE}✓ Ripgrep:${NC} $(rg --version | head -n1)"
echo -e "${BLUE}✓ Pwgen:${NC} $(pwgen --version 2>&1 | head -n1)"
echo -e "${BLUE}✓ FFmpeg:${NC} $(ffmpeg -version 2>&1 | head -n1)"
echo -e "${BLUE}✓ FileZilla:${NC} $(filezilla --version 2>&1 | head -n1 || echo 'Installed')"
echo -e "${BLUE}✓ AWS CLI:${NC} $(aws --version)"
echo -e "${BLUE}✓ Terraform:${NC} $(terraform version | head -n1)"
echo -e "${BLUE}✓ GitHub CLI:${NC} $(gh --version | head -n1)"
echo -e "${BLUE}✓ Pandoc:${NC} $(pandoc --version | head -n1)"
if command -v codex >/dev/null 2>&1; then
    echo -e "${BLUE}✓ OpenAI Codex:${NC} $(codex --version 2>/dev/null || echo 'Available')"
else
    echo -e "${YELLOW}⚠ OpenAI Codex:${NC} Available after terminal restart"
fi
if command -v claude >/dev/null 2>&1; then
    echo -e "${BLUE}✓ Claude Code:${NC} $(claude --version 2>/dev/null || echo 'Available')"
else
    echo -e "${YELLOW}⚠ Claude Code:${NC} Available after terminal restart"
fi
if command -v gemini >/dev/null 2>&1; then
    echo -e "${BLUE}✓ Gemini CLI:${NC} $(gemini --version 2>/dev/null || echo 'Available')"
else
    echo -e "${YELLOW}⚠ Gemini CLI:${NC} Available after terminal restart"
fi
if command -v grok >/dev/null 2>&1; then
    echo -e "${BLUE}✓ Grok CLI:${NC} $(grok --version 2>/dev/null || echo 'Available')"
else
    echo -e "${YELLOW}⚠ Grok CLI:${NC} Available after terminal restart"
fi
echo
echo -e "${YELLOW}Complete installation log saved to: ~/Desktop/NEXT_STEPS.txt${NC}"
echo -e "${GREEN}Your Ubuntu coding workstation is ready!${NC}"

# Write final summary to log file
echo "" >> "$LOG_FILE"
echo "=== FINAL INSTALLATION SUMMARY ===" >> "$LOG_FILE"
echo "Chrome: $(google-chrome --version)" >> "$LOG_FILE"
echo "Git: $(git --version)" >> "$LOG_FILE"
echo "VS Code: $(code --version | head -n1)" >> "$LOG_FILE"
echo "Docker: $(docker --version)" >> "$LOG_FILE"
echo "Node.js: $(node --version)" >> "$LOG_FILE"
echo "Python: $(python3 --version)" >> "$LOG_FILE"
echo "boto3: $(python3 -c 'import boto3; print(boto3.__version__)' 2>/dev/null || echo 'Installed')" >> "$LOG_FILE"
echo "pytest: $(pytest --version 2>/dev/null | head -n1 || echo 'Installed')" >> "$LOG_FILE"
echo "black: $(black --version 2>/dev/null | head -n1 || echo 'Installed')" >> "$LOG_FILE"
echo "Ripgrep: $(rg --version | head -n1)" >> "$LOG_FILE"
echo "Pwgen: $(pwgen --version 2>&1 | head -n1)" >> "$LOG_FILE"
echo "FFmpeg: $(ffmpeg -version 2>&1 | head -n1)" >> "$LOG_FILE"
echo "FileZilla: $(filezilla --version 2>&1 | head -n1 || echo 'Installed')" >> "$LOG_FILE"
echo "AWS CLI: $(aws --version)" >> "$LOG_FILE"
echo "Terraform: $(terraform version | head -n1)" >> "$LOG_FILE"
echo "GitHub CLI: $(gh --version | head -n1)" >> "$LOG_FILE"
echo "Pandoc: $(pandoc --version | head -n1)" >> "$LOG_FILE"
if command -v codex >/dev/null 2>&1; then
    echo "OpenAI Codex: $(codex --version 2>/dev/null || echo 'Available')" >> "$LOG_FILE"
else
    echo "OpenAI Codex: Available after terminal restart" >> "$LOG_FILE"
fi
if command -v claude >/dev/null 2>&1; then
    echo "Claude Code: $(claude --version 2>/dev/null || echo 'Available')" >> "$LOG_FILE"
else
    echo "Claude Code: Available after terminal restart" >> "$LOG_FILE"
fi
if command -v gemini >/dev/null 2>&1; then
    echo "Gemini CLI: $(gemini --version 2>/dev/null || echo 'Available')" >> "$LOG_FILE"
else
    echo "Gemini CLI: Available after terminal restart" >> "$LOG_FILE"
fi
if command -v grok >/dev/null 2>&1; then
    echo "Grok CLI: $(grok --version 2>/dev/null || echo 'Available')" >> "$LOG_FILE"
else
    echo "Grok CLI: Available after terminal restart" >> "$LOG_FILE"
fi
echo "" >> "$LOG_FILE"
echo "Installation completed at: $(date)" >> "$LOG_FILE"

log "Applications installed successfully! Pin Chrome and VS Code to your dash for quick access."
