#!/usr/bin/env bash

#
# macOS Installation Script
# Usage: curl -fsSL https://static.due.ren/install.sh | bash
#
# This script installs:
# - Homebrew (if not installed)
# - CLI tools via Homebrew formulas
# - GUI applications via Homebrew casks
# - Mac App Store applications (requires sign-in)
# - Google Fonts (Barlow, Poppins)
#

set -e  # Exit on error

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

print_section() {
  printf "\n${GREEN}==>${NC} %s\n" "$1"
}

print_error() {
  printf "${RED}ERROR:${NC} %s\n" "$1"
}

print_warning() {
  printf "${YELLOW}WARNING:${NC} %s\n" "$1"
}

print_info() {
  printf "${GREEN}✓${NC} %s\n" "$1"
}

# Check if running on macOS
if [[ "$(uname)" != "Darwin" ]]; then
  print_error "This script only works on macOS"
  exit 1
fi

# =============================================================================
# STEP 1: Install Xcode Command Line Tools
# =============================================================================

print_section "Checking Xcode Command Line Tools..."

if ! xcode-select -p &> /dev/null; then
  print_info "Installing Xcode CLI tools..."
  xcode-select --install

  printf "\n${YELLOW}💡 Please complete the Xcode installation in the popup window.${NC}\n"
  read -p "Press ENTER after installation is complete... "
else
  print_info "Xcode CLI tools already installed"
fi

# =============================================================================
# STEP 2: Install Homebrew
# =============================================================================

print_section "Installing Homebrew..."

if ! command -v brew &> /dev/null; then
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  # Determine Homebrew path based on architecture
  if [[ "$(/usr/bin/arch)" == "arm64" ]]; then
    BREW_PATH="/opt/homebrew/bin/brew"
  else
    BREW_PATH="/usr/local/bin/brew"
  fi

  # Add to shell profile for future sessions
  if [[ ! -f "$HOME/.zprofile" ]] || ! grep -q "brew shellenv" "$HOME/.zprofile"; then
    echo >> "$HOME/.zprofile"
    echo "eval \"\$($BREW_PATH shellenv)\"" >> "$HOME/.zprofile"
  fi

  # Set up PATH for current session
  eval "$($BREW_PATH shellenv)"

  print_info "Homebrew installed successfully"
else
  print_info "Homebrew already installed"
  eval "$(brew shellenv)"
fi

# =============================================================================
# STEP 3: Install Homebrew Formulas (CLI Tools)
# =============================================================================

print_section "Installing Homebrew Formulas (CLI tools)..."

# Add custom taps
print_info "Adding custom taps..."
brew tap artginzburg/tap
brew tap domt4/autoupdate

FORMULAS=(
  "atuin"                         # Shell history
  "bash"                          # Updated bash
  "bash-completion"               # Bash completions
  "pinentry-mac"                  # GPG pin entry (required for brew autoupdate --sudo)
  "artginzburg/tap/sudo-touchid"  # Touch ID for sudo
  "gemini-cli"                    # Gemini AI CLI
  "ffmpeg"                        # Media processing
  "mas"                           # Mac App Store CLI
  "mole"                          # SSH tunneling
  "rename"                        # Rename utility
  "ykman"                         # YubiKey manager
)

for formula in "${FORMULAS[@]}"; do
  if brew list --formula | grep -q "^${formula}\$"; then
    print_info "$formula already installed"
  else
    print_info "Installing $formula..."
    brew install "$formula"
  fi
done

# =============================================================================
# STEP 4: Install Homebrew Casks (GUI Applications)
# =============================================================================

print_section "Installing Homebrew Casks (GUI applications)..."

CASKS=(
  "eloston-chromium" # Ungoogled Chromium browser
  "deepl"            # DeepL translator
  "element"          # Matrix client
  "signal"           # Signal messenger
  "nextcloud-vfs"    # Nextcloud sync (with virtual files support)
  "proton-drive"     # Proton Drive
  "proton-mail"      # Proton Mail
  "protonvpn"        # Proton VPN
  "claude-code"      # Claude AI coding assistant
  "codex"            # AI coding assistant
  "nova"             # Nova editor
  "transmit"         # FTP client
  "trimmy"           # Video trimmer
)

# Add custom tap for codexbar
print_info "Adding custom taps..."
brew tap steipete/tap

CUSTOM_CASKS=(
  "steipete/tap/codexbar" # AI assistant menu bar
)

for cask in "${CASKS[@]}"; do
  if brew list --cask | grep -q "^${cask}\$"; then
    print_info "$cask already installed"
  else
    print_info "Installing $cask..."
    brew install --cask "$cask"
  fi
done

# Install custom tap casks
for cask in "${CUSTOM_CASKS[@]}"; do
  cask_name="${cask##*/}"
  if brew list --cask | grep -q "^${cask_name}\$"; then
    print_info "$cask_name already installed"
  else
    print_info "Installing $cask_name..."
    brew install --cask "$cask"
  fi
done

# =============================================================================
# STEP 5: Install Mac App Store Applications
# =============================================================================

print_section "Installing Mac App Store applications..."

# Check if user is signed into App Store
if ! mas account &> /dev/null; then
  print_warning "Not signed into Mac App Store"
  printf "Please sign in to the App Store, then press ENTER to continue... "
  read
fi

# Check that mas is available
if ! command -v mas &> /dev/null; then
  print_error "mas CLI not found. Please run: brew install mas"
  exit 1
fi

MAS_APPS=(
  "1352778147:Bitwarden"
  "1503970375:Invoice Ninja"
  "409203825:Numbers"
  "409201541:Pages"
  "1503446680:PastePal"
  "1579902068:xSearch"
)

for app in "${MAS_APPS[@]}"; do
  app_id="${app%%:*}"
  app_name="${app##*:}"

  if mas list | grep -q "^${app_id}"; then
    print_info "$app_name already installed"
  else
    print_info "Installing $app_name..."
    mas install "$app_id" || print_warning "Failed to install $app_name (may need to purchase first)"
  fi
done

# =============================================================================
# STEP 6: Install Google Fonts
# =============================================================================

print_section "Installing Google Fonts..."

FONT_DIR="$HOME/Library/Fonts"
mkdir -p "$FONT_DIR"

# Download and install Barlow font family
if [[ ! -f "$FONT_DIR/Barlow-Regular.ttf" ]]; then
  print_info "Downloading Barlow font family..."
  curl -fsSL "https://fonts.google.com/download?family=Barlow" -o /tmp/Barlow.zip
  unzip -q -o /tmp/Barlow.zip -d /tmp/Barlow
  cp /tmp/Barlow/*.ttf "$FONT_DIR/" 2>/dev/null || true
  rm -rf /tmp/Barlow /tmp/Barlow.zip
  print_info "Barlow installed"
else
  print_info "Barlow already installed"
fi

# Download and install Barlow Semi Condensed
if [[ ! -f "$FONT_DIR/BarlowSemiCondensed-Regular.ttf" ]]; then
  print_info "Downloading Barlow Semi Condensed font family..."
  curl -fsSL "https://fonts.google.com/download?family=Barlow%20Semi%20Condensed" -o /tmp/BarlowSemiCondensed.zip
  unzip -q -o /tmp/BarlowSemiCondensed.zip -d /tmp/BarlowSemiCondensed
  cp /tmp/BarlowSemiCondensed/*.ttf "$FONT_DIR/" 2>/dev/null || true
  rm -rf /tmp/BarlowSemiCondensed /tmp/BarlowSemiCondensed.zip
  print_info "Barlow Semi Condensed installed"
else
  print_info "Barlow Semi Condensed already installed"
fi

# Download and install Poppins
if [[ ! -f "$FONT_DIR/Poppins-Regular.ttf" ]]; then
  print_info "Downloading Poppins font family..."
  curl -fsSL "https://fonts.google.com/download?family=Poppins" -o /tmp/Poppins.zip
  unzip -q -o /tmp/Poppins.zip -d /tmp/Poppins
  cp /tmp/Poppins/*.ttf "$FONT_DIR/" 2>/dev/null || true
  rm -rf /tmp/Poppins /tmp/Poppins.zip
  print_info "Poppins installed"
else
  print_info "Poppins already installed"
fi

# Download and install Berkeley Mono
if [[ ! -f "$FONT_DIR/BerkeleyMono-Regular.otf" ]]; then
  print_info "Downloading Berkeley Mono font family..."
  curl -fsSL "https://static.due.ren/site/font/BerkeleyMono-Regular.otf" -o "$FONT_DIR/BerkeleyMono-Regular.otf"
  curl -fsSL "https://static.due.ren/site/font/BerkeleyMono-Bold.otf" -o "$FONT_DIR/BerkeleyMono-Bold.otf"
  curl -fsSL "https://static.due.ren/site/font/BerkeleyMono-Oblique.otf" -o "$FONT_DIR/BerkeleyMono-Oblique.otf"
  curl -fsSL "https://static.due.ren/site/font/BerkeleyMono-Bold-Oblique.otf" -o "$FONT_DIR/BerkeleyMono-Bold-Oblique.otf"
  print_info "Berkeley Mono installed"
else
  print_info "Berkeley Mono already installed"
fi

# =============================================================================
# STEP 7: Configure macOS System Preferences
# =============================================================================

print_section "Configuring macOS system preferences..."

# Hide the Dock
print_info "Hiding Dock automatically"
defaults write com.apple.dock autohide -bool true

# Show hard disks on desktop
print_info "Showing hard disks on desktop"
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true

# Show user home folder in Finder sidebar
print_info "Adding user home folder to Finder sidebar"
defaults write com.apple.sidebarlists systemitems -dict-add ShowUserHome -bool true

# Show all file extensions
print_info "Showing all file extensions"
defaults write NSGlobalDomain AppleShowAllExtensions -bool true

# Remove items from trash after 30 days
print_info "Setting trash to empty after 30 days"
defaults write com.apple.finder FXRemoveOldTrashItems -bool true

# Safari: Open with all windows from last session
print_info "Configuring Safari to restore all windows from last session"
defaults write com.apple.Safari AlwaysRestoreSessionAtLaunch -bool true 2>/dev/null || \
  print_warning "Safari preference may need to be set manually in Safari > Settings > General"

# Restart affected applications
print_info "Restarting Finder and Dock to apply changes"
killall Finder 2>/dev/null || true
killall Dock 2>/dev/null || true

# =============================================================================
# STEP 8: Configure Post-Install Services
# =============================================================================

print_section "Configuring services..."

# Create LaunchAgents directory if it doesn't exist
mkdir -p "$HOME/Library/LaunchAgents"

# Enable automatic Homebrew updates
print_info "Enabling automatic Homebrew updates (every 12 hours)"
brew autoupdate start 43200 --upgrade --cleanup --immediate --sudo 2>/dev/null || print_warning "Failed to configure brew autoupdate"

# =============================================================================
# COMPLETION
# =============================================================================

print_section "Installation Complete!"

printf "\n${GREEN}✓${NC} All software has been installed successfully!\n"
printf "\n${YELLOW}Next steps:${NC}\n"
printf "  1. Restart your terminal to use Homebrew commands\n"
printf "  2. Enable Touch ID for sudo: ${GREEN}sudo brew services start artginzburg/tap/sudo-touchid${NC}\n"
printf "  3. Configure installed applications as needed\n"
printf "\n${GREEN}Enjoy your new macOS setup!${NC}\n\n"
