# To get this script and run copy and paste the following in to the terminal:
# bash <(curl -s https://gist.githubusercontent.com/martynhaigh/b45d9370995e48a4cd5354e8305652ab/raw/new_mac_setup.sh)
if [ `uname -s` != "Darwin" ]; then
  printf "  โ—๏ธ  This only works on a Mac\n"
  exit
fi

DEBUG=false

while getopts d: flag
do
    case "${flag}" in
        d) DEBUG=true;;
    esac
done

prompt_confirm() {
  while true; do
    read -r -n 1 -p "  ๐Ÿ’ฌ ${1:-Continue?} [y/n]: " REPLY
    case $REPLY in
      [yY]) echo ; ANSWER="Y" ; return 0 ;;
      [nN]) echo ; ANSWER="N" ; return 1 ;;
      *) printf " \033[31m %s \n\033[0m" "invalid input"
    esac
  done
}
clear

if [ "$DEBUG" = true ]; then
  echo "@ = $@\n"
  echo "0 = $0\n"
  echo "dollar = $$"
  echo "ZSH Version $ZSH_VERSION"
fi

echo "*************************************************************************"
echo "**                              Mac Setup                              **"
echo "*************************************************************************"
echo -e "\n"

if !(id -Gn `id -un` | grep -w -q admin);
then
    printf "  โ—๏ธ  Please run under an admin account\n"
    exit
fi

printf "  ๐Ÿ”ถ  Ask for the administrator password for the duration of this script\n"
sudo -v

printf "  ๐Ÿ”ถ  Keep-alive: update existing sudo time stamp until .osx has finished\n"
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &

if xcode-select --print-path > /dev/null; then
  printf "\n  โœ…  Command Line Tools installed.\n"
else
  printf "\n  โ—๏ธ  Command Line Tools are not installed.\n"
  printf "  ๐Ÿ”ถ  Attempting to install Command Line Tools...\n"
  xcode-select --install
  printf "  โœ…  Command Line Tools installed.\n"
fi

# Check for Homebrew,
# Install if we don't have it
if test ! $(which brew); then
  printf "\n  ๐Ÿ”ถ  Installing Homebrew...\n"
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  echo '# Set PATH, MANPATH, etc., for Homebrew.' >> ~/.profile
  echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.profile
  echo '# Set PATH, MANPATH, etc., for Homebrew.' >> ~/.zprofile
  echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
  eval "$(/opt/homebrew/bin/brew shellenv)"
  printf "  โœ…  Homebrew installed\n\n"
else
  printf "\n  ๐Ÿ”ถ  Homebrew already installed. Setting Permissions..."
  sudo chown -R $(whoami) $(brew --prefix)/*
  printf "โœ… \n\n"
fi

# Update homebrew recipes
printf "  ๐Ÿ”ถ  Updating homebrew...\n"
brew update
brew upgrade
brew doctor
printf "  โœ…  Homebrew updated\n\n"

if [ ! -d '/Applications/iTerm.app' -a ! -d "$HOME/Applications/iTerm.app" ]; then
  printf "  ๐Ÿ”ถ  Installing iTerm..."
  brew install iterm2
  printf " โœ…\n\n"

  printf "  ๐Ÿ”ถ  Install iterm zsh integrations...\n"
  curl -L https://iterm2.com/shell_integration/install_shell_integration.sh | bash
  compaudit | xargs chmod g-w,o-w
  source $HOME/.iterm2_shell_integration.zsh
  printf "  โœ…  Iterm zsh integrations installed\n"
fi

if [ ! "$TERM_PROGRAM" == "iTerm.app" ]; then
  printf "  โ—๏ธ  Please run following command with iterm (copied to clipboard):\n"
  printf "original command: $ORIGINAL_COMMAND"
  printf "bash <(curl -s https://gist.githubusercontent.com/martynhaigh/b45d9370995e48a4cd5354e8305652ab/raw/new_mac_setup.sh)"
  echo "bash <(curl -s https://gist.githubusercontent.com/martynhaigh/b45d9370995e48a4cd5354e8305652ab/raw/new_mac_setup.sh)" | pbcopy
  open -a iTerm.app
  exit
else
  printf "  โœ…  Running in iTerm\n\n"
fi

#Install Zsh & Oh My Zsh
if [ ! omz ]; then
  printf "\n  ๐Ÿ”ถ  Installing Oh My ZSH...\n"
  sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
  printf "  โœ…  Oh My ZSH installed\n\n"
else
  printf "  โœ…  Oh My ZSH already installed\n\n"
fi

# if [[ $SHELL = "zsh" ]]; then
#   printf "  โœ…  Default shell is ZSH\n\n"
# else
#   printf "  ๐Ÿ”ถ  Setting ZSH as shell..."
#   chsh -s /bin/zsh
#   printf "  Set โœ…\n\n"
#   printf "  โ—๏ธ  Please run following command with zsh (copied to clipboard):\n"
#   printf "original command: $ORIGINAL_COMMAND"
#   printf "bash <(curl -s https://gist.githubusercontent.com/martynhaigh/b45d9370995e48a4cd5354e8305652ab/raw/new_mac_setup.sh)"
#   echo "bash <(curl -s https://gist.githubusercontent.com/martynhaigh/b45d9370995e48a4cd5354e8305652ab/raw/new_mac_setup.sh)" | pbcopy
#   zsh
# fi

printf "  ๐Ÿ”ถ  Installing git\n"
brew install git
printf "  โœ…  Git installed\n\n"

prompt_confirm "Would you like to install a browser?"
if [[ $ANSWER =~ ^[yY]$ ]]; then
  printf "  ๐Ÿ”ถ  Select your browser of choice for setup\n"
  tmpPS3=PS3
  PS3='> '
  select opt in "Firefox Developer Edition" "Firefox" "Chrome" "Quit"
  do
      printf "  ๐Ÿ”ถ  Installing $opt\n"
      case $opt in
          "Firefox Developer Edition")
              brew install --cask firefox-developer-edition &> /dev/null;
              ;;
          "Firefox")
              brew install --cask firefox &> /dev/null;
              ;;
          "Chrome")
              brew install --cask google-chrome &> /dev/null;
              ;;
          "Quit")
              break
              ;;
          *) printf "invalid option $ANSWER\n";;
      esac
      printf "  โœ…  $opt Installed\n"
      prompt_confirm   "   Would you like to set $opt as your default browser?"
      if [[ $ANSWER =~ ^([yY][eE][sS]|[yY])$ ]]; then
        printf "\n  ๐Ÿ”ถ  Setting $opt as default browser\n"
        case $opt in
            "Firefox Developer Edition")
                /Applications/Firefox\ Developer\ Edition.app/Contents/MacOS/firefox -setDefaultBrowser
                ;;
            "Firefox")
                /Applications/Firefox.app/Contents/MacOS/firefox -setDefaultBrowser
                ;;
            "Chrome")
                open -a "Google Chrome" --args --make-default-browser
                ;;
        esac
      fi

      printf "  โœ…  Default browser set\n\n"
      prompt_confirm   "   Do you want to install another browser?"
      if [[ $ANSWER =~ ^[nN]$ ]]; then
        break
      fi
  done
  PS3=tmpPS3
fi

prompt_confirm "Would you like to setup a new SSH key and add it to github? "
if [[ $ANSWER =~ ^[yY]$ ]]; then
  if [ -f ~/.ssh/github.pub ]; then
    printf "\n  โœ…  SSH Key exists.\n\n"
  else
    printf "\n  ๐Ÿ”ถ  Setting up your SSH key...\n"
    ssh-keygen -t rsa -b 4096 -f ~/.ssh/github
    printf "  โœ…  SSH Key created.\n"
  fi

	read -p "  ๐Ÿ”ถ  Login to lastpass (to get github PW) - Press any key to continue" -n 1 -r
	open https://lastpass.com/?ac=1
	read -p "  ๐Ÿ”ถ  Press any key to continue" -n 1 -r

  read -p "  ๐Ÿ”ถ  Login to github - Press any key to continue" -n 1 -r
	open http://github.com

  printf "\n  ๐Ÿ”ถ  Copying public key to the clipboard...\n"
  pbcopy < ~/.ssh/github.pub
  printf "\n  โœ…  SSH Key copied to the clipboard.\n\n"

	read -p  "  ๐Ÿ”ถ  Log on to Github to add your SSH key - press any key when you're ready" -n 1 -r
	open https://github.com/settings/ssh/new
  read -p "  ๐Ÿ”ถ  Press any key to continue...  " -n 1 -r
  printf "\n\n  โœ…  SSH key added to Github\n"

fi


prompt_confirm "Would you like to copy the dotfiles from github?"
if [[ $ANSWER =~ ^[yY]$ ]]; then
	printf "\n  ๐Ÿ”ถ  Copying dotfiles from Github\n"
	cd ~
	git clone git@github.com:martynhaigh/dotfiles.git .dotfiles
	cd .dotfiles
	mv ~/.ssh/github ~/.ssh/github
	mv ~/.ssh/github.pub ~/.ssh/github.pub
	sh init.sh
  printf "  โœ…  dot files installed and setup\n\n"
fi

prompt_confirm "Would you like to install apps from the app store?"
if [[ $ANSWER =~ ^[yY]$ ]]; then
  brew install mas
  masapps=(
    "Xcode:497799835"
    "Airmail 3:918858936"
    "Affinity Designer:824171161"
    "Microsoft OneNote:784801555"
    "Affinity Photo:824183456"
    "Fantastical:975937182"
    "Things:904280696"
    "Keeper Password Manager:414781829"
    "Quiver:866773894"
    "Amphetamine:937984704"
    "SnippetsLab:1006087419"
  )

  printf "  ๐Ÿ”ถ  Installing apps from app store\n"
  for app in "${masapps[@]}"; do

    KEY="${app%%:*}"
    VALUE="${app##*:}"
    prompt_confirm "Would you like to install $KEY ?"

    if [[ $ANSWER =~ ^[yY]$ ]]; then
      mas install $VALUE
    fi
  done
fi


sudo xcodebuild -license accept

printf "  ๐Ÿ”ถ  Installing command line applications from Brew...\n"
brew install tree fzf ack
brew install wget
brew install trash
brew install mackup
brew install pidcat
brew install thefuck
brew install zsh-completions
brew install zsh-autosuggestions
brew install zsh-syntax-highlighting
# https://github.com/tj/git-extras/blob/master/Commands.md
brew install git-extras
brew install autojump

brew install scrcpy
brew install dockutil

# Bartender replacement
brew install jordanbaird-ice

# Needed for pyenv
brew install Pygments

printd "  ๐Ÿ”ถ  Installing python"
curl https://pyenv.run | bash

eval "$(pyenv virtualenv-init -)"

# Update pyenv itself to ensure you have the latest version
pyenv update

# Install the latest Python 2.x release
# Find the latest 2.x version available
latest_2x=$(pyenv install --list | grep '^  2' | tail -n 1 | awk '{print $1}')
# Install it
pyenv install "${latest_2x}"

# Install the latest Python 3.x release
latest_3x=$(pyenv install --list | grep -v - | grep -v a | grep -v b | grep -v t | tail -1 | tr -d ' ')
pyenv install "${latest_3x}"

# Set global Python versions
pyenv global "${latest_2x}" "${latest_3x}"


# Apps
apps=(
  alfred
  android-studio
  appcleaner
  bettertouchtool
  charles
  cheatsheet
  contexts
  doxie
  flipper
  google-drive
  istat-menus
  noun-project
  obsidian
  spotify
  suspicious-package
  visual-studio-code
)

# quick look plugins (https://github.com/sindresorhus/quick-look-plugins)
quicklookplugins=(
  glance
  qlmarkdown
  qlstephen
  qlcolorcode
  quicklook-json
  qlprettypatch
  quicklook-csv
  qlimagesize
  webpquicklook
  quicklookase
  qlvideo
)

# Install apps to /Applications
# Default is: /Users/$user/Applications

printf "  ๐Ÿ”ถ  Installing Homebrew binaries...\n"
for i in "${apps[@]}"
do
  prompt_confirm "Would you like to install $i ?"

  if [[ $ANSWER =~ ^[yY]$ ]]; then
    brew install --cask --appdir="/Applications" $i
  fi

done
printf "  โœ…  Brew binaries installed\n"

printf "  ๐Ÿ”ถ  Installing quick look plugins with Cask...\n"
for i in "${quicklookplugins[@]}"
do
  prompt_confirm "Would you like to install $i ?"

  if [[ $ANSWER =~ ^[yY]$ ]]; then
    brew install --cask --appdir="/Applications" $i
  fi
done
printf "  โœ…  Brew quick look plugins installed\n"

printf "  ๐Ÿ”ถ  Cleaning up Brew...\n"
brew cleanup
printf "  โœ…  Brew cleaned\n"




printf "  ๐Ÿ”ถ  Configuring MacOS...\n"

printf "  ๐Ÿ”ถ  Close any open System Preferences panes, to prevent them from overriding settings weโ€™re about to change\n"
osascript -e 'tell application "System Preferences" to quit'

prompt_confirm  "Would you like to set your computer name (as done via System Preferences >> Sharing)?"
if [[ $ANSWER =~ ^[yY]$ ]]; then
  printf "\n  ๐Ÿ”ถ  What would you like the human readable computer name to be? (e.g. Martyn's MBP)\n"
  read COMPUTER_NAME
  printf "  ๐Ÿ”ถ  What would you like the host name to be? (e.g. martyn-mbp)\n"
  read HOST_NAME
  sudo scutil --set ComputerName "$COMPUTER_NAME"
  sudo scutil --set HostName $HOST_NAME
  sudo scutil --set LocalHostName $HOST_NAME
  sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string $HOST_NAME
  printf "  โœ…  Computer name set.\n"
fi

printf "  ๐Ÿ”น Disable the sound effects on boot\n"
rm -rf /private/var/folders/*/*/-Caches-/com.apple.dock.iconcache

printf "  ๐Ÿ”น Close any open System Preferences panes, to prevent them from overriding settings weโ€™re about to change\n"
osascript -e 'tell application "System Preferences" to quit'

printf "  ๐Ÿ”น Disable the sound effects on boot\n"
sudo nvram SystemAudioVolume=" "

printf "  ๐Ÿ”น Disabling system-wide resume\n"
defaults write NSGlobalDomain NSQuitAlwaysKeepsWindows -bool false

printf "  ๐Ÿ”น Set Help Viewer windows to non-floating mode\n"
defaults write com.apple.helpviewer DevMode -bool true

printf "  ๐Ÿ”น Disabling automatic termination of inactive apps\n"
defaults write NSGlobalDomain NSDisableAutomaticTermination -bool true

printf "  ๐Ÿ”น Allow text selection in Quick Look\n"
defaults write com.apple.finder QLEnableTextSelection -bool TRUE

printf "  ๐Ÿ”น Disable automatic capitalization as itโ€™s annoying when typing code\n"
defaults write NSGlobalDomain NSAutomaticCapitalizationEnabled -bool false

printf "  ๐Ÿ”น Disable automatic period substitution as itโ€™s annoying when typing code\n"
defaults write NSGlobalDomain NSAutomaticPeriodSubstitutionEnabled -bool false

printf "  ๐Ÿ”น Disable auto-correct\n"
defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false

printf "  ๐Ÿ”น Disabling OS X Gate Keeper\n"
printf "   (You'll be able to install any app you want from here on, not just Mac App Store apps)\n"
sudo spctl --master-disable
sudo defaults write /var/db/SystemPolicy-prefs.plist enabled -string no
# Disable the โ€œAre you sure you want to open this application?โ€ dialog
defaults write com.apple.LaunchServices LSQuarantine -bool false

printf "  ๐Ÿ”น Remove duplicates in the โ€œOpen Withโ€ menu (also see `lscleanup` alias)\n"
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user

printf "  ๐Ÿ”น Expanding the save panel by default\n"
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool true

printf "  ๐Ÿ”น Expanding the print panel by default\n"
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool true

printf "  ๐Ÿ”น Automatically quit printer app once the print jobs complete\n"
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true

printf "  ๐Ÿ”น Saving to disk (not to iCloud) by default\n"
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false

printf "  ๐Ÿ”น Disable smart quotes as theyโ€™re annoying when typing code\n"
defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false

printf "  ๐Ÿ”น Disable smart dashes as theyโ€™re annoying when typing code\n"
defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false

printf "  ๐Ÿ”น Enabling full keyboard access for all controls (e.g. enable Tab in modal dialogs)\n"
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3

printf "  ๐Ÿ”น Disabling press-and-hold for keys in favour of a key repeat\n"
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false

printf "  ๐Ÿ”น Set a blazingly fast keyboard repeat rate\n"
defaults write NSGlobalDomain KeyRepeat -int 2
defaults write NSGlobalDomain InitialKeyRepeat -int 15

printf "  ๐Ÿ”น Setting trackpad & mouse speed to a reasonable number\n"
defaults write -g com.apple.trackpad.scaling 2
defaults write -g com.apple.mouse.scaling 2.5

printf "  ๐Ÿ”น Enabling subpixel font rendering on non-Apple LCDs\n"
defaults write NSGlobalDomain AppleFontSmoothing -int 2

printf "  ๐Ÿ”น Enabling snap-to-grid for icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Preventing Time Machine from prompting to use new hard drives as backup volume\n"
defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true

printf "  ๐Ÿ”น Disable the sudden motion sensor as its not useful for SSDs\n"
sudo pmset -a sms 0

printf "  ๐Ÿ”น Speeding up wake from sleep to 24 hours from an hour\n"
# http://www.cultofmac.com/221392/quick-hack-speeds-up-retina-macbooks-wake-from-sleep-os-x-tips/
sudo pmset -a standbydelay 86400


printf "  ๐Ÿ”น Setting screenshots location to $HOME/Screenshots\n"
mkdir $HOME/Screenshots
defaults write com.apple.screencapture location "$HOME/Screenshots"
dockutil --add $HOME/Screenshots --display stack --sort dateadded
defaults write com.apple.screencapture "show-thumbnail" "0"

printf "  ๐Ÿ”น Setting screenshot format to PNG\n"
defaults write com.apple.screencapture type -string "png"

printf "  ๐Ÿ”น Disable 'natural' (Lion-style) scrolling\n"
defaults write NSGlobalDomain com.apple.swipescrolldirection -bool false

printf "  ๐Ÿ”น Always show scrollbars\n"
defaults write NSGlobalDomain AppleShowScrollBars -string "Always"

printf "  ๐Ÿ”น Increase window resize speed for Cocoa applications\n"
defaults write NSGlobalDomain NSWindowResizeTime -float 0.001

printf "  ๐Ÿ”น Automatically illuminate built-in MacBook keyboard in low light\n"
defaults write com.apple.BezelServices kDim -bool true

printf "  ๐Ÿ”น Turn off keyboard illumination when computer is not used for 5 minutes\n"
defaults write com.apple.BezelServices kDimTime -int 300

printf "  ๐Ÿ”น Show IP address, hostname, OS version when clicking the clock in the login window\n"
sudo defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo HostName

#printf "  ๐Ÿ”น Never go into computer sleep mode\n"
#systemsetup -setcomputersleep Off > /dev/null

printf "  ๐Ÿ”น Trackpad: enable tap to click for this user and for the login screen\n"
# System Preferences > Trackpad > Tap to click
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true
defaults -currentHost write NSGlobalDomain com.apple.mouse.tapBehavior -int 1
defaults write NSGlobalDomain com.apple.mouse.tapBehavior -int 1

# System Preferences > Accessibility > Mouse & Trackpad > Trackpad Potions
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerDrag -bool true
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadThreeFingerDrag -bool true

printf "  ๐Ÿ”น Trackpad: Set Mission control & app expose to three fingers\n"
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadThreeFingerVertSwipeGesture -int 0
defaults write com.apple.AppleMultitouchTrackpad TrackpadThreeFingerVertSwipeGesture -int 0

printf "  ๐Ÿ”น Trackpad: map bottom right corner to right-click\n"
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -int 2
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true
defaults -currentHost write NSGlobalDomain com.apple.trackpad.trackpadCornerClickBehavior -int 1
defaults -currentHost write NSGlobalDomain com.apple.trackpad.enableSecondaryClick -bool true

printf "  ๐Ÿ”น Increase sound quality for Bluetooth headphones/headsets\n"
defaults write com.apple.BluetoothAudioAgent "Apple Bitpool Min (editable)" -int 40

printf "  ๐Ÿ”น Enable full keyboard access for all controls\n"
printf "   (e.g. enable Tab in modal dialogs)\n"
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3

printf "  ๐Ÿ”น Require password immediately after sleep or screen saver begins\n"
defaults write com.apple.screensaver askForPassword -int 1
defaults write com.apple.screensaver askForPasswordDelay -int 0

printf "  ๐Ÿ”น Enable snap-to-grid for icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Setting dark/light Auto Select mode (reboot required)\n"
#sudo defaults write /Library/Preferences/.GlobalPreferences.plist _HIEnableThemeSwitchHotKey -bool true
defaults write -globalDomain AppleInterfaceStyleSwitchesAutomatically -bool true

printf "  ๐Ÿ”น Empty Trash securely by default\n"
defaults write com.apple.finder EmptyTrashSecurely -bool true

# printf "  ๐Ÿ”น Automatically hide and show the Dock\n"
# defaults write com.apple.dock autohide -bool true

printf "  ๐Ÿ”น Click in the scrollbar to: Jump to the spot that's clicked\n"
# System Preferences > General > Click in the scrollbar to: Jump to the spot that's clicked
defaults write -globalDomain AppleScrollerPagingBehavior -bool true

###############################################################################
# Menu bar                                                                      #
###############################################################################

printf "  ๐Ÿ”น Show battery percentage\n"
defaults write com.apple.menuextra.battery ShowPercent YES

defaults write com.apple.systemuiserver menuExtras -array \
	"/System/Library/CoreServices/Menu Extras/Bluetooth.menu" \
	"/System/Library/CoreServices/Menu Extras/TimeMachine.menu" \
	"/System/Library/CoreServices/Menu Extras/Battery.menu" \
	"/System/Library/CoreServices/Menu Extras/Clock.menu" \
	"/System/Library/CoreServices/Menu Extras/Volume.menu" \
	"/System/Library/CoreServices/Menu Extras/User.menu"

###############################################################################
# Finder                                                                      #
###############################################################################
printf "  ๐Ÿ”น Adding home to finder sidebar\n"
# Get the Username of the currently logged user
loggedInUser=`/bin/ls -l /dev/console | /usr/bin/awk '{ print $3 }'`
if [ -e /usr/local/bin/mysides ]
then
  mysides add Home file:///Users/$loggedInUser && sleep 2
fi

printf "  ๐Ÿ”น Finder: allow quitting via โŒ˜ + Q; doing so will also hide desktop icons\n"
defaults write com.apple.finder QuitMenuItem -bool true

printf "  ๐Ÿ”น Finder: Set sidebar icon size to AppleInterfaceStyleSwitchesAutomatically\n"
# System Preferences > General > Sidebar icon size: Medium
defaults write -globalDomain NSTableViewDefaultSizeMode -int 1

printf "  ๐Ÿ”น Finder: disable window animations and Get Info animations\n"
defaults write com.apple.finder DisableAllAnimations -bool true

printf "  ๐Ÿ”น Set Desktop as the default location for new Finder windows\n"
# For other paths, use `PfLo` and `file:///full/path/here/`
defaults write com.apple.finder NewWindowTarget -string "PfDe"
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}/Desktop/"

printf "  ๐Ÿ”น Show icons for hard drives, servers, and removable media on the desktop\n"
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowMountedServersOnDesktop -bool true
defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

printf "  ๐Ÿ”น Finder: show hidden files by default\n"
defaults write com.apple.finder AppleShowAllFiles -bool true

printf "  ๐Ÿ”น Finder: show all filename extensions\n"
# Finder > Preferences > Show all filename extensions
defaults write NSGlobalDomain AppleShowAllExtensions -bool true

printf "  ๐Ÿ”น Finder: show status bar\n"
defaults write com.apple.finder ShowStatusBar -bool true

printf "  ๐Ÿ”น Finder: show path bar\n"
# Finder > View > Show Path Bar
defaults write com.apple.finder ShowPathbar -bool true

printf "  ๐Ÿ”น Display full POSIX path as Finder window title\n"
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true

printf "  ๐Ÿ”น Don't show warning before removing from iCloud Drive\n"
# Finder > Preferences > Show warning before removing from iCloud Drive
defaults write com.apple.finder FXEnableRemoveFromICloudDriveWarning -bool false

printf "  ๐Ÿ”น Keep folders on top when sorting by name\n"
defaults write com.apple.finder _FXSortFoldersFirst -bool true

printf "  ๐Ÿ”น When performing a search, search the current folder by default\n"
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"

printf "  ๐Ÿ”น Disable the warning when changing a file extension\n"
# Finder > Preferences > Show wraning before changing an extension
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false

printf "  ๐Ÿ”น Enable spring loading for directories\n"
defaults write NSGlobalDomain com.apple.springing.enabled -bool true

printf "  ๐Ÿ”น Remove the spring loading delay for directories\n"
defaults write NSGlobalDomain com.apple.springing.delay -float 0

printf "  ๐Ÿ”น Avoid creating .DS_Store files on network or USB volumes\n"
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true

printf "  ๐Ÿ”น Disable disk image verification\n"
defaults write com.apple.frameworks.diskimages skip-verify -bool true
defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true
defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true

printf "  ๐Ÿ”น Automatically open a new Finder window when a volume is mounted\n"
defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool true
defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool true
defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool true

printf "  ๐Ÿ”น Show item info near icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Show item info to the right of the icons on the desktop\n"
/usr/libexec/PlistBuddy -c "Set DesktopViewSettings:IconViewSettings:labelOnBottom false" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Enable snap-to-grid for icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Increase grid spacing for icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Increase the size of icons on the desktop and in other icon views\n"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist
/usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist

printf "  ๐Ÿ”น Use list view in all Finder windows by default\n"
# Four-letter codes for the other view modes: `icnv`, `clmv`, `glyv`
# Finder > View > As List
defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv"

printf "  ๐Ÿ”น Disable the warning before emptying the Trash\n"
defaults write com.apple.finder WarnOnEmptyTrash -bool false

printf "  ๐Ÿ”น Enable AirDrop over Ethernet and on unsupported Macs running Lion\n"
defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true

printf "  ๐Ÿ”น Show the ~/Library folder\n"
chflags nohidden ~/Library && xattr -d com.apple.FinderInfo ~/Library

printf "  ๐Ÿ”น Show the /Volumes folder\n"
sudo chflags nohidden /Volumes

# printf "  ๐Ÿ”น Remove Dropboxโ€™s green checkmark icons in Finder\n"
# file=/Applications/Dropbox.app/Contents/Resources/emblem-dropbox-uptodate.icns
# [ -e "${file}" ] && mv -f "${file}" "${file}.bak"

printf "  ๐Ÿ”น Expand the following File Info panes:\n"
printf "   โ€œGeneralโ€, โ€œOpen withโ€, and โ€œSharing & Permissionsโ€\n"
defaults write com.apple.finder FXInfoPanesExpanded -dict \
	General -bool true \
	OpenWith -bool true \
	Privileges -bool true

###############################################################################
# Dock, Dashboard, and hot corners                                            #
###############################################################################

printf "  ๐Ÿ”น Remove all dock icons\n"
defaults write com.apple.dock persistent-apps -array

# Enable highlight hover effect for the grid view of a stack (Dock)
defaults write com.apple.dock mouse-over-hilite-stack -bool true

printf "  ๐Ÿ”น Setting the icon size of Dock items to 36 pixels for optimal size/screen-realestate\n"
# System Preferences > Dock > Size:
# Set the icon size of Dock items to 36 pixels
defaults write com.apple.dock tilesize -int 36

printf "  ๐Ÿ”น Change minimize/maximize window effect\n"
# System Preferences > Dock > Minimize windows using: Scale effect
defaults write com.apple.dock mineffect -string "scale"

printf "  ๐Ÿ”น  Minimize windows into their applicationโ€™s icon\n"
# System Preferences > Dock > Minimize windows into application icon
defaults write com.apple.dock minimize-to-application -bool true

printf "  ๐Ÿ”น  Enable spring loading for all Dock items\n"
defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true

printf "  ๐Ÿ”น  Show indicator lights for open applications in the Dock\n"
# System Preferences > Dock > Show indicators for open applications
defaults write com.apple.dock show-process-indicators -bool true

printf "  ๐Ÿ”น  Wipe all (default) app icons from the Dock\n"
# This is only really useful when setting up a new Mac, or if you donโ€™t use
# the Dock to launch apps.
defaults write com.apple.dock persistent-apps -array

# Show only open applications in the Dock
#defaults write com.apple.dock static-only -bool true

printf "  ๐Ÿ”น  Donโ€™t animate opening applications from the Dock\n"
defaults write com.apple.dock launchanim -bool false

printf "  ๐Ÿ”น  Speed up Mission Control animations\n"
defaults write com.apple.dock expose-animation-duration -float 0.1

printf "  ๐Ÿ”น  Donโ€™t group windows by application in Mission Control\n"
# (i.e. use the old Exposรฉ behavior instead)
defaults write com.apple.dock expose-group-by-app -bool false

printf "  ๐Ÿ”น  Disable Dashboard\n"
defaults write com.apple.dashboard mcx-disabled -bool true

printf "  ๐Ÿ”น  Donโ€™t show Dashboard as a Space\n"
# System Preferences > Mission Controll > Dashboard
defaults write com.apple.dock dashboard-in-overlay -bool true

printf "  ๐Ÿ”น  Donโ€™t automatically rearrange Spaces based on most recent use\n"
# System Preferences > Mission Controll > Automatically rearrange Spaces based on most recent use
defaults write com.apple.dock mru-spaces -bool false

printf "  ๐Ÿ”น  Setting Dock to auto-hide and removing the auto-hiding delay\n"
# System Preferences > Dock > Automatically hide and show the Dock:
defaults write com.apple.dock autohide -bool true

printf "  ๐Ÿ”น  Automatically hide and show the Dock (duration)\n"
# System Preferences > Dock > Automatically hide and show the Dock (duration)
defaults write com.apple.dock autohide-time-modifier -float 0

printf "  ๐Ÿ”น  Remove the auto-hiding Dock delay\n"
# System Preferences > Dock > Automatically hide and show the Dock (delay)
defaults write com.apple.dock autohide-delay -float 0

printf "  ๐Ÿ”น  Automatically hide and show the Dock\n"
defaults write com.apple.dock autohide -bool true

printf "  ๐Ÿ”น  Make Dock icons of hidden applications translucent\n"
defaults write com.apple.dock showhidden -bool true

printf "  ๐Ÿ”น  Donโ€™t show recent applications in Dock\n"
defaults write com.apple.dock show-recents -bool false

printf "  ๐Ÿ”น  Disable the Launchpad gesture (pinch with thumb and three fingers)\n"
#defaults write com.apple.dock showLaunchpadGestureEnabled -int 0

printf "  ๐Ÿ”น  Reset Launchpad, but keep the desktop wallpaper intact\n"
find "${HOME}/Library/Application Support/Dock" -name "*-*.db" -maxdepth 1 -delete

printf "  ๐Ÿ”น  Add a spacer to the right side of the Dock (where the Trash is)\n"
defaults write com.apple.dock persistent-others -array-add '{tile-data={}; tile-type="spacer-tile";}'

# Hot corners
# Possible values:
#  0: no-op
#  2: Mission Control
#  3: Show application windows
#  4: Desktop
#  5: Start screen saver
#  6: Disable screen saver
#  7: Dashboard
# 10: Put display to sleep
# 11: Launchpad
# 12: Notification Center
# 13: Lock Screen
# Top left screen corner โ†’ Mission Control

printf "  ๐Ÿ”น  Set bottom right hot corner โ†’ Mission Control\n"
defaults write com.apple.dock wvous-br-corner -int 2
defaults write com.apple.dock wvous-br-modifier -int 0

printf "  ๐Ÿ”น  Set top right hot corner โ†’ Desktop\n"
defaults write com.apple.dock wvous-tr-corner -int 4
defaults write com.apple.dock wvous-tr-modifier -int 0

printf "  ๐Ÿ”น  Set left screen corner โ†’ Start screen saver\n"
defaults write com.apple.dock wvous-bl-corner -int 5
defaults write com.apple.dock wvous-bl-modifier -int 0

printf "  ๐Ÿ”น  System Preferences > Dock > Magnification\n"
defaults write com.apple.dock magnification -bool true

printf "  ๐Ÿ”น  System Preferences > Dock > Size (magnified)\n"
defaults write com.apple.dock largesize -int 54



###############################################################################
# Safari & WebKit                                                             #
###############################################################################

# Privacy: donโ€™t send search queries to Apple
defaults write com.apple.Safari UniversalSearchEnabled -bool false
defaults write com.apple.Safari SuppressSearchSuggestions -bool true


###############################################################################
# Spotlight                                                                   #
###############################################################################

# Change indexing order and disable some search results
# Yosemite-specific search results (remove them if you are using macOS 10.9 or older):
# 	MENU_DEFINITION
# 	MENU_CONVERSION
# 	MENU_EXPRESSION
# 	MENU_SPOTLIGHT_SUGGESTIONS (send search queries to Apple)
# 	MENU_WEBSEARCH             (send search queries to Apple)
# 	MENU_OTHER
defaults write com.apple.spotlight orderedItems -array \
	'{"enabled" = 1;"name" = "APPLICATIONS";}' \
	'{"enabled" = 1;"name" = "SYSTEM_PREFS";}' \
	'{"enabled" = 1;"name" = "DIRECTORIES";}' \
	'{"enabled" = 1;"name" = "PDF";}' \
	'{"enabled" = 1;"name" = "FONTS";}' \
	'{"enabled" = 0;"name" = "DOCUMENTS";}' \
	'{"enabled" = 0;"name" = "MESSAGES";}' \
	'{"enabled" = 0;"name" = "CONTACT";}' \
	'{"enabled" = 0;"name" = "EVENT_TODO";}' \
	'{"enabled" = 0;"name" = "IMAGES";}' \
	'{"enabled" = 0;"name" = "BOOKMARKS";}' \
	'{"enabled" = 0;"name" = "MUSIC";}' \
	'{"enabled" = 0;"name" = "MOVIES";}' \
	'{"enabled" = 0;"name" = "PRESENTATIONS";}' \
	'{"enabled" = 0;"name" = "SPREADSHEETS";}' \
	'{"enabled" = 0;"name" = "SOURCE";}' \
	'{"enabled" = 0;"name" = "MENU_DEFINITION";}' \
	'{"enabled" = 0;"name" = "MENU_OTHER";}' \
	'{"enabled" = 0;"name" = "MENU_CONVERSION";}' \
	'{"enabled" = 0;"name" = "MENU_EXPRESSION";}' \
	'{"enabled" = 0;"name" = "MENU_WEBSEARCH";}' \
	'{"enabled" = 0;"name" = "MENU_SPOTLIGHT_SUGGESTIONS";}'
# Load new settings before rebuilding the index
killall mds > /dev/null 2>&1
# Make sure indexing is enabled for the main volume
sudo mdutil -i on / > /dev/null
# Rebuild the index from scratch
sudo mdutil -E / > /dev/null


###############################################################################
# iTerm 2                                                          #
###############################################################################

printf "  ๐Ÿ”น  Donโ€™t display the annoying prompt when quitting iTerm\n"
defaults write com.googlecode.iterm2 PromptOnQuit -bool false

###############################################################################
# Time Machine                                                                #
###############################################################################

printf "  ๐Ÿ”น  Prevent Time Machine from prompting to use new hard drives as backup volume\n"
defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true

# Disable local Time Machine backups
#hash tmutil &> /dev/null && sudo tmutil disablelocal

###############################################################################
# Activity Monitor                                                            #
###############################################################################

printf "  ๐Ÿ”น  Show the main window when launching Activity Monitor\n"
defaults write com.apple.ActivityMonitor OpenMainWindow -bool true

printf "  ๐Ÿ”น  Visualize CPU usage in the Activity Monitor Dock icon\n"
defaults write com.apple.ActivityMonitor IconType -int 2

printf "  ๐Ÿ”น  Show all processes in Activity Monitor\n"
defaults write com.apple.ActivityMonitor ShowCategory -int 0

printf "  ๐Ÿ”น  Sort Activity Monitor results by CPU usage\n"
defaults write com.apple.ActivityMonitor SortColumn -string "CPUUsage"
defaults write com.apple.ActivityMonitor SortDirection -int 0


###############################################################################
# Mac App Store                                                               #
###############################################################################

printf "  ๐Ÿ”น  Enable the automatic update check\n"
defaults write com.apple.SoftwareUpdate AutomaticCheckEnabled -bool true

printf "  ๐Ÿ”น  Check for software updates daily, not just once per week\n"
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1

printf "  ๐Ÿ”น  Download newly available updates in background\n"
defaults write com.apple.SoftwareUpdate AutomaticDownload -int 1

printf "  ๐Ÿ”น  Install System data files & security updates\n"
defaults write com.apple.SoftwareUpdate CriticalUpdateInstall -int 1

printf "  ๐Ÿ”น  Automatically download apps purchased on other Macs\n"
defaults write com.apple.SoftwareUpdate ConfigDataInstall -int 1

printf "  ๐Ÿ”น  Turn on app auto-update\n"
defaults write com.apple.commerce AutoUpdate -bool true

printf "  ๐Ÿ”น  Allow the App Store to reboot machine on macOS updates\n"
defaults write com.apple.commerce AutoUpdateRestartRequired -bool true


###############################################################################
# Photos                                                                      #
###############################################################################

printf "  ๐Ÿ”น  Prevent Photos from opening automatically when devices are plugged in\n"
defaults -currentHost write com.apple.ImageCapture disableHotPlug -bool true


###############################################################################
# Menubar                                                                      #
###############################################################################

printf "  ๐Ÿ”น  Set fast user switching menu to display as icon\n"
defaults write .GlobalPreferences userMenuExtraStyle -int 2

mkdir $HOME/Screenshots
defaults write com.apple.dock persistent-others -array-add "<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>file:///$HOME/Screenshots</string><key>_CFURLStringType</key><integer>15</integer></dict><key>file-type</key><integer>32</integer></dict><key>tile-type</key><string>file-tile</string></dict>"

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

printf "  ๐Ÿ”น  Kill affected apps\n"
for app in "Dashboard" "Terminal" "Dock" "Finder" "SystemUIServer"; do
  killall "${app}" > /dev/null 2>&1
done

printf "  ๐Ÿ”ถ  Note that some of these changes require a logout/restart to take effect.\n"

printf "  ๐Ÿ”ถ  Here's a list of things you can't automate yet:\n"
printf "  ๐Ÿ”น  Install the screensaver\n"
open https://github.com/JohnCoates/Aerial
# printf "  ๐Ÿ”น  Open Alfred, and set the preferences folder to the one in Dropbox\n"
printf "  ๐Ÿ”น  Open Android Studio and install everything\n"
printf "  ๐Ÿ”น  Next, run and set up all the apps that should start every time you log in.\n"
printf "  ๐Ÿ”น    BTT, iStats, Alfred, Noizio"
printf "  โœ…  Done!\n"

git clone git@github.com:martynhaigh/dotfiles.git ~/.dotfiles
cd ~/.dotfiles && ./install -q

touch ~/.hushlogin