#!/usr/bin/env bash
# Based on https://github.com/mathiasbynens/dotfiles/blob/main/.macos

SCRIPTDIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"


# Close any open System Preferences panes, to prevent them from overriding
# settings we’re about to change
osascript -e 'tell application "System Preferences" to quit'

# Ask for the administrator password upfront
sudo -v

# Keep-alive: update existing `sudo` time stamp until `.macos` has finished
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &

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

# Always show scrollbars
defaults write NSGlobalDomain AppleShowScrollBars -string "Always"
# Possible values: `WhenScrolling`, `Automatic` and `Always`

# Expand save panel by default
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool true

# Expand print panel by default
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true
defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool true

# Automatically quit printer app once the print jobs complete
defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true

# Display ASCII control characters using caret notation in standard text views
# Try e.g. `cd /tmp; unidecode "\x{0000}" > cc.txt; open -e cc.txt`
defaults write NSGlobalDomain NSTextShowsControlCharacters -bool true

# Disable Resume system-wide
defaults write com.apple.systempreferences NSQuitAlwaysKeepsWindows -bool false

# Reveal IP address, hostname, OS version, etc. when clicking the clock
# in the login window
sudo defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo HostName

# Disable automatic period substitution as it’s annoying when typing code
defaults write NSGlobalDomain NSAutomaticPeriodSubstitutionEnabled -bool false

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

# Finder: allow quitting via ⌘ + Q; doing so will also hide desktop icons
defaults write com.apple.finder QuitMenuItem -bool true

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

# Hide icons for hard drives, servers, and removable media on the desktop
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool false
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool false
defaults write com.apple.finder ShowMountedServersOnDesktop -bool false
defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool false

# Finder: show hidden files by default
#defaults write com.apple.finder AppleShowAllFiles -bool true

# Finder: show all filename extensions
defaults write NSGlobalDomain AppleShowAllExtensions -bool true

# Finder: show status bar
defaults write com.apple.finder ShowStatusBar -bool true

# Finder: show path bar
defaults write com.apple.finder ShowPathbar -bool true

# Display full POSIX path as Finder window title
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true

# Keep folders on top when sorting by name
# defaults write com.apple.finder _FXSortFoldersFirst -bool true

# When performing a search, search the current folder by default
# defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"

# Enable spring loading for directories
# defaults write NSGlobalDomain com.apple.springing.enabled -bool true

# Remove the spring loading delay for directories
# defaults write NSGlobalDomain com.apple.springing.delay -float 0

# Avoid creating .DS_Store files on network or USB volumes
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true

# Automatically open a new Finder window when a volume is mounted
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

# Show item info near icons on the desktop and in other icon views
# /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

# Show item info to the right of the icons on the desktop
# /usr/libexec/PlistBuddy -c "Set DesktopViewSettings:IconViewSettings:labelOnBottom false" ~/Library/Preferences/com.apple.finder.plist

# Enable snap-to-grid for icons on the desktop and in other icon views
/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

# Increase grid spacing for icons on the desktop and in other icon views
# /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

# Increase the size of icons on the desktop and in other icon views
# /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

# Use list view in all Finder windows by default
# Four-letter codes for the other view modes: `icnv`, `clmv`, `glyv`
defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv"

# Enable AirDrop over Ethernet and on unsupported Macs running Lion
defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true

# Show the ~/Library folder
# chflags nohidden ~/Library && xattr -d com.apple.FinderInfo ~/Library

# Show the /Volumes folder
sudo chflags nohidden /Volumes

# Expand the following File Info panes:
# “General”, “Open with”, and “Sharing & Permissions”
defaults write com.apple.finder FXInfoPanesExpanded -dict \
	General -bool true \
	OpenWith -bool true \
	Privileges -bool true

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

# Wipe all (default) app icons from the Dock
# 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

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

# Show the main window when launching Activity Monitor
defaults write com.apple.ActivityMonitor OpenMainWindow -bool true

# Visualize CPU usage in the Activity Monitor Dock icon
defaults write com.apple.ActivityMonitor IconType -int 5

# Show all processes in Activity Monitor
defaults write com.apple.ActivityMonitor ShowCategory -int 0

# Sort Activity Monitor results by CPU usage
defaults write com.apple.ActivityMonitor SortColumn -string "CPUUsage"
defaults write com.apple.ActivityMonitor SortDirection -int 0

###############################################################################
# Ice                                                                         #
###############################################################################

# Ice has to be terminated, otherwise it would overwrite the configuration upon closing
killall "Ice" &> /dev/null
defaults write com.jordanbaird.Ice AutoRehide -bool true
defaults write com.jordanbaird.Ice CanToggleAlwaysHiddenSection -bool true
defaults write com.jordanbaird.Ice CustomIceIconIsTemplate -bool false
defaults write com.jordanbaird.Ice EnableAlwaysHiddenSection -bool true
defaults write com.jordanbaird.Ice HideApplicationMenus -bool true
defaults write com.jordanbaird.Ice IceBarLocation -int 0
defaults write com.jordanbaird.Ice ItemSpacingOffset -float "-12"
# See readme how to get and convert the data to hex
defaults write com.jordanbaird.Ice MenuBarAppearanceConfigurationV2 -data [encoded data, 125744 characters]
defaults write com.jordanbaird.Ice RehideInterval -float "15"
defaults write com.jordanbaird.Ice RehideStrategy -int 0
defaults write com.jordanbaird.Ice SUAutomaticallyUpdate -bool true
defaults write com.jordanbaird.Ice SUEnableAutomaticChecks -bool true
defaults write com.jordanbaird.Ice SUSendProfileInfo -bool false
defaults write com.jordanbaird.Ice ShowAllSectionsOnUserDrag -bool true
defaults write com.jordanbaird.Ice ShowIceIcon -bool true
defaults write com.jordanbaird.Ice ShowOnClick -bool true
defaults write com.jordanbaird.Ice ShowOnHover -bool false
defaults write com.jordanbaird.Ice ShowOnScroll -bool true
defaults write com.jordanbaird.Ice ShowSectionDividers -bool true
defaults write com.jordanbaird.Ice TempShowInterval -float "15"
defaults write com.jordanbaird.Ice UseIceBar -bool true
defaults write com.jordanbaird.Ice hasMigrated0_8_0 -bool true
defaults write com.jordanbaird.Ice hasMigrated0_10_1 -bool true
defaults write com.jordanbaird.Ice hasMigrated0_10_0 -bool true

###############################################################################
# Moom                                                                        #
###############################################################################

# Moom has to be terminated, otherwise it would overwrite the configuration upon closing
killall "Moom" &> /dev/null
sleep 3
defaults import com.manytricks.Moom ${SCRIPTDIR}/../config/plist/Moom.plist

###############################################################################
# Alfred                                                                      #
###############################################################################

# Alfred has to be terminated, otherwise it would overwrite the configuration upon closing
killall "Alfred" &> /dev/null
killall "Alfred Preferences" &> /dev/null
defaults import com.runningwithcrayons.Alfred-Preferences ${SCRIPTDIR}/../config/plist/Alfred-Preferences.plist


###############################################################################
# AlDente                                                                     #
###############################################################################

killall "AlDente" &> /dev/null
defaults write com.apphousekitchen.aldente-pro SUEnableAutomaticChecks -int 1
defaults write com.apphousekitchen.aldente-pro automaticDischarge -int 1
defaults write com.apphousekitchen.aldente-pro chargeVal -int 80
defaults write com.apphousekitchen.aldente-pro checkForUpdates -int 1
defaults write com.apphousekitchen.aldente-pro clamshellDischargeMessage -int 0
defaults write com.apphousekitchen.aldente-pro completelyDisableSleep -int 0
defaults write com.apphousekitchen.aldente-pro exitInhibitCharge -int 0
defaults write com.apphousekitchen.aldente-pro heatProtectMode -int 1
defaults write com.apphousekitchen.aldente-pro helpMessage -int 0
defaults write com.apphousekitchen.aldente-pro launchAtLogin -int 1
defaults write com.apphousekitchen.aldente-pro lockScreenWhenClosed -int 0
defaults write com.apphousekitchen.aldente-pro lpmMenuBarColor -int 1
defaults write com.apphousekitchen.aldente-pro lpmPreference -int 0
defaults write com.apphousekitchen.aldente-pro magsafeBlinkDischarge -int 1
defaults write com.apphousekitchen.aldente-pro magsafeControl -int 1
defaults write com.apphousekitchen.aldente-pro menuBarIconStyle -int 1
defaults write com.apphousekitchen.aldente-pro noMenubarIcon -int 0
defaults write com.apphousekitchen.aldente-pro popoverAnimation -int 0
defaults write com.apphousekitchen.aldente-pro popoverBatteryInfoList -array -string designCapacity -string adapterName -string batteryPower -string macosCondition -string macosCapacity -string timeToFull -string temperature -string batteryVoltage -string lowPowerMode -string adapterCurrent -string adapterSerial -string batteryCurrent -string serialNumber -string systemLoad -string maxCapacity -string cycleCount -string adapterVoltage -string adapterPower -string adapterManufacturer
defaults write com.apphousekitchen.aldente-pro popoverWidgets -array -string highAppUsage -string powerflow -string stats
defaults write com.apphousekitchen.aldente-pro sailingLevel -int 10
defaults write com.apphousekitchen.aldente-pro sailingMode -int 1
defaults write com.apphousekitchen.aldente-pro scheduleElements -array -string '{"name":"Calibrate","action":2,"active":true,"repeatInterval":5,"id":"E199007E-E0D4-448F-B325-879AEE9943C5","percentage":80,"startDate":773128856.633131}'
defaults write com.apphousekitchen.aldente-pro settingsLock -int 0
defaults write com.apphousekitchen.aldente-pro showDockIcon -int 0
defaults write com.apphousekitchen.aldente-pro showGUIonStartup -int 0
defaults write com.apphousekitchen.aldente-pro showHelperInstallationMessage -int 1
defaults write com.apphousekitchen.aldente-pro showPercentage -int 1
defaults write com.apphousekitchen.aldente-pro showPercentagePopover -int 1
defaults write com.apphousekitchen.aldente-pro sleepInhibitCharge -int 0
defaults write com.apphousekitchen.aldente-pro startTasksAfterDue -int 1
defaults write com.apphousekitchen.aldente-pro useRealPercentage -int 0


###############################################################################
# Terminal & iTerm 2                                                          #
###############################################################################

# Only use UTF-8 in Terminal.app
defaults write com.apple.terminal StringEncodings -array 4

# Install the Solarized Dark theme for iTerm
open "${HOME}/.files/config/iTerm2/theme/ayu Dark.itermcolors"
open "${HOME}/.files/config/iTerm2/theme/ayu Light.itermcolors"
open "${HOME}/.files/config/iTerm2/theme/ayu Mirage.itermcolors"

###############################################################################
# Sublime Text                                                                #
###############################################################################

# Install Sublime Text settings
[[ ! -f ~/Library/Application\ Support/Sublime\ Text*/Packages/User/Preferences.sublime-settings ]] && cp -r "${SCRIPTDIR}/config/sublimetext/Preferences.sublime-settings" ~/Library/Application\ Support/Sublime\ Text*/Packages/User/Preferences.sublime-settings 2> /dev/null

###############################################################################
# Kill affected applications                                                  #
###############################################################################

for app in "Activity Monitor" \
	"cfprefsd" \
	"Dock" \
	"Finder" \
	"SystemUIServer" \
	"Terminal"; do
	killall "${app}" &> /dev/null
done

###############################################################################
# Open default applications again                                             #
###############################################################################

for app in "AlDente" \
  "Alfred 5" \
  "Ice" \
  "Moom"; do
  [[ -d "/Applications/${app}.app" ]] && open "/Applications/${app}.app" || [[ -d "${HOME}/Applications/${app}.app" ]] && open "${HOME}/Applications/${app}.app" || true
done

echo "Done. Note that some of these changes require a logout/restart to take effect."