#!/bin/bash

clear
echo "macx.sh by ~zotan, bootstrapping system..."
echo
echo "--- Opening sudo session ---"
# From https://gist.github.com/cowboy/3118588
sudo -v
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
caffeinate -disu -w $$ &
echo
echo "--- Installing Rosetta 2 ---"
/usr/sbin/softwareupdate --install-rosetta --agree-to-license

echo
echo "--- Installing homebrew ---"
set -e
NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
(echo; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"') >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
export HOMEBREW_CASK_OPTS="--no-quarantine"
set +e

echo
echo "--- Cloning os-bootstrap-core ---"
mkdir ~/.os-bootstrap
git clone https://git.ztn.sh/zotan/os-bootstrap-core ~/.os-bootstrap/core

echo
echo "--- Linking to system Brewfile ---"
ln -s ~/.os-bootstrap/core/macx-resources/Brewfile ~/.Brewfile

echo
echo "--- Running brew bundle ---"
brew bundle --global

echo
echo "--- Running postinstall steps ---"
echo "Configuring pinentry-mac"
mkdir -p ~/.gnupg
echo "pinentry-program /opt/homebrew/bin/pinentry-mac" >> ~/.gnupg/gpg-agent.conf

echo "Configuring dock autohide"
defaults write com.apple.dock autohide -int 1
defaults write com.apple.dock autohide-delay -int 0
defaults write com.apple.dock autohide-time-modifier -float 0.4
killall Dock

echo "Disabling font smoothing"
defaults -currentHost write -g AppleFontSmoothing -int 0

echo "Fixing dotnet symlink"
sudo ln -s /opt/homebrew/opt/dotnet/libexec /usr/local/share/dotnet

echo "Installing DNSSEC root anchor for ldns and drill"
mkdir -p /opt/homebrew/opt/ldns/etc/unbound
cp ~/Projects/macx-resources/dnssec-root.key /opt/homebrew/opt/ldns/etc/unbound/root.key

echo "Configuring global gitignore"
echo ".DS_Store" > ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global

echo "Configuring zshrc"
curl -L ztn.sh/macx-resources/zshrc >> ~/.zshrc

echo "Installing prezto"
rm ~/.zprofile
curl -L ztn.sh/prezto.sh | zsh
(echo; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"') >> ~/.zprofile

####
echo
echo "--- macx.sh bootstrap complete ---"
echo
echo "iOS applications not installed automatically:    bunq"
echo "Other applications not installed automatically:  Amphetamine Enhancer, Capture One, u-he hive, Arturia Software Center"
echo "Setapp applications not installed automatically: TablePlus, Screens, RapidAPI, WiFi Explorer, Archiver, Proxyman"
echo
echo "Please download and install them manually."
echo
echo "After that, please reboot to make sure everything is applied."
echo
