#!/usr/bin/env bash

# Mac OS X configuration
#
# This configuration applies to the latest version of macOS (currently 11.3),
# and sets up preferences and configurations for all the built-in services and
# apps. Third-party app config should be done elsewhere.
#
# Options:
#   --no-restart: Don't restart any apps or services after running the script.
#
# If you want to figure out what default needs changing, do the following:
#
#   1. `cd /tmp`
#   2. Store current defaults in file: `defaults read > before`
#   3. Make a change to your system.
#   4. Store new defaults in file: `defaults read > after`
#   5. Diff the files: `diff before after`
#
# @see: http://secrets.blacktree.com/?showapp=com.apple.finder
# @see: https://github.com/herrbischoff/awesome-macos-command-line
#
# @author Billy-George Price-Sprackland

# Warn that some commands will not be run if the script is not run as root.
if [[ $EUID -ne 0 ]]; then
  RUN_AS_ROOT=false
  printf "Certain commands will not be run without sudo privileges. To run as root, run the same command prepended with 'sudo', for example: $ sudo $0\n\n" | fold -s -w 80
else
  RUN_AS_ROOT=true
  while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
fi

set_symbolic_hotkey() {
  local id="$1"
  local enabled="$2"
  local key_char="$3"
  local key_code="$4"
  local modifiers="$5"
  local plist="${HOME}/Library/Preferences/com.apple.symbolichotkeys.plist"

  defaults write com.apple.symbolichotkeys AppleSymbolicHotKeys -dict-add "${id}" "<dict><key>enabled</key><${enabled}/><key>value</key><dict><key>parameters</key><array><integer>${key_char}</integer><integer>${key_code}</integer><integer>${modifiers}</integer></array><key>type</key><string>standard</string></dict></dict>"

  # Keep the on-disk plist honest even when cfprefsd has a stale cached value.
  /usr/libexec/PlistBuddy -c "Set :AppleSymbolicHotKeys:${id}:enabled ${enabled}" "${plist}" >/dev/null 2>&1 || true
}

refresh_symbolic_hotkeys() {
  defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys >/dev/null 2>&1 || true

  if [[ -x /System/Library/PrivateFrameworks/SystemAdministration.framework/Resources/activateSettings ]]; then
    /System/Library/PrivateFrameworks/SystemAdministration.framework/Resources/activateSettings -u >/dev/null 2>&1 || true
  fi
}

###############################################################################
# General UI/UX                                                               #
###############################################################################

defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true

if [[ "$RUN_AS_ROOT" = true ]]; then
  systemsetup -setrestartfreeze on
fi

defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false
defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false

osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/System/Library/Desktop Pictures/Solid Colors/Stone.png"'

###############################################################################
# Trackpad, mouse, keyboard, Bluetooth accessories, and input                 #
###############################################################################

defaults write com.apple.AppleMultitouchTrackpad FirstClickThreshold -int 0
defaults write com.apple.AppleMultitouchTrackpad ActuationStrength -int 0

defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true
defaults write com.apple.AppleMultitouchTrackpad TrackpadRightClick -bool true

# Use the bottom-right trackpad corner for secondary click.
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -int 2
defaults write com.apple.AppleMultitouchTrackpad TrackpadCornerSecondaryClick -int 2

defaults write NSGlobalDomain ContextMenuGesture -int 1

defaults write NSGlobalDomain InitialKeyRepeat -int 20
defaults write NSGlobalDomain KeyRepeat -int 1

defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false

###############################################################################
# Screen                                                                      #
###############################################################################

defaults write com.apple.screencapture location -string "${HOME}/Downloads"
defaults write com.apple.screencapture type -string "png"
defaults write com.apple.screencapture disable-shadow -bool true

###############################################################################
# Keyboard Shortcuts                                                          #
###############################################################################

# Disable screenshot shortcuts.
set_symbolic_hotkey 28 false 51 20 1179648 # Save picture of screen as a file
set_symbolic_hotkey 29 false 51 20 1441792 # Copy picture of screen to clipboard
set_symbolic_hotkey 30 false 52 21 1179648 # Save picture of selected area as a file
set_symbolic_hotkey 31 false 52 21 1441792 # Copy picture of selected area to clipboard
set_symbolic_hotkey 184 false 53 23 1179648 # Screenshot and recording options

# Disable Spotlight and Show Apps shortcuts.
set_symbolic_hotkey 64 false 32 49 1048576 # Show Spotlight search
set_symbolic_hotkey 65 false 32 49 1572864 # Show Finder search window
set_symbolic_hotkey 160 false 65535 65535 0 # Show Apps
refresh_symbolic_hotkeys

###############################################################################
# Finder                                                                      #
###############################################################################

defaults write com.apple.finder NewWindowTarget -string "PfDe"
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}/Desktop/"

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

defaults write NSGlobalDomain AppleShowAllExtensions -bool false

defaults write com.apple.finder ShowStatusBar -bool true
defaults write com.apple.finder QLEnableTextSelection -bool true
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false

defaults write NSGlobalDomain com.apple.springing.enabled -bool true
defaults write NSGlobalDomain com.apple.springing.delay -float 0.1

defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true

###############################################################################
# Dock                                                                        #
###############################################################################

defaults write com.apple.dock tilesize -int 30
defaults write com.apple.dock expose-animation-duration -float 0.15
defaults write com.apple.dock showhidden -bool true
defaults write com.apple.dock show-recents -bool false
defaults write com.apple.universalaccess reduceTransparency -bool true

defaults write com.apple.dock wvous-br-corner -int 2
defaults write com.apple.dock wvous-br-modifier -int 0

defaults write com.apple.dock wvous-tr-corner -int 10
defaults write com.apple.dock wvous-tr-modifier -int 0

defaults write com.apple.dock wvous-bl-corner -int 4
defaults write com.apple.dock wvous-bl-modifier -int 0

###############################################################################
# Safari                                                                      #
###############################################################################

defaults write com.apple.Safari IncludeDevelopMenu -bool true
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true

###############################################################################
# Mail                                                                        #
###############################################################################

defaults write com.apple.mail AddressesIncludeNameOnPasteboard -bool false

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

if [[ "$RUN_AS_ROOT" = true ]]; then
  sudo defaults write /.Spotlight-V100/VolumeConfiguration Exclusions -array "/Volumes"
  killall mds > /dev/null 2>&1
fi

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

defaults write com.apple.ActivityMonitor OpenMainWindow -bool true
defaults write com.apple.ActivityMonitor ShowCategory -int 0

###############################################################################
# Messages                                                                    #
###############################################################################

defaults write com.apple.messageshelper.MessageController SOInputLineSettings -dict-add "automaticQuoteSubstitutionEnabled" -bool false
defaults write com.apple.messageshelper.MessageController SOInputLineSettings -dict-add "continuousSpellCheckingEnabled" -bool false

###############################################################################
# App Store                                                                   #
###############################################################################

defaults write com.apple.appstore InAppReviewEnabled -int 0

###############################################################################
# Kill/restart affected applications                                          #
###############################################################################

if [[ ! ($* == *--no-restart*) ]]; then
  for app in "cfprefsd" "Dock" "Finder" "Mail" "SystemUIServer" "Terminal"; do
    killall "${app}" > /dev/null 2>&1
  done
fi

killall SystemUIServer > /dev/null 2>&1

printf "Please log out and log back in to make all settings take effect.\n"
