{{- if (ne .host.distro.family "windows") -}}
#!/usr/bin/env bash
# @file Homebrew / Xcode Tools Installation
# @brief Ensures Xcode tools are installed on macOS and ensures Homebrew is installed on either Linux or macOS
# @description
#     This script ensures macOS has tools like `git` by installing the Xcode command-line developer tools if they are
#     not already installed. Then, on both Linux and macOS, it ensures Homebrew is installed.
#
#     It also tries to perform a system update and there may be some manual work required since it is not possible
#     to completely automate the system update process for macOS.
#
#     ## Environment Variables
#
#     * `NO_RESTART` - Set this variable to skip restarts triggered by system updates on macOS
#
#     ## Homebrew Requirement
#
#     Install Doctor relies on Homebrew for many tools that are currently only available via Homebrew. Removing the dependency
#     would be a nice-to-have but there are currently no plans for supporting systems without Homebrew installed.

{{ includeTemplate "universal/profile-before" }}
{{ includeTemplate "universal/logg-before" }}

### Configure Firewall
# TODO: If this is required, notes should be added describing the pros / cons of the security
# if [ -d /Applications ] && [ -d /System ]; then
#   logg info 'Disabling the block all incoming traffic option in the system Firewall settings'
#   /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall off || (logg error 'Failed to disable incoming traffic block in the system Firewall' && logg info 'Manually disable the option under "System Preferences" > "Network" > "Firewall" > "Incoming Traffic Block Toggle"')
# fi

### System upgrade on macOS
# Note: If a shutdown is required and the `softwareupdate` command restart command does not work then `m shutdown -f` might be useful or `m restart -f`
# Do you want to terminate running processes in this window?
# Closing this window will terminate the running processes: softwareupdate, sudo
# Running sudo softwareupdate -i -a -R --agree-to-license reboots just not in the script due to the running processes perhaps
# Check for pending reboot by checking 
if [ -d /Applications ] && [ -d /Library ] && [ -z "$NO_RESTART" ]; then
  logg info 'Applying OS upgrades (if available)'
  sudo softwareupdate -i -a --agree-to-license || logg error 'Failed to trigger a system update via sudo softwareupdate -i -a --agree-to-license --background'
  logg info 'If system updates are downloaded / installed, a reboot might be required.'
  ### Source: https://community.jamf.com/t5/jamf-pro/determine-if-update-requires-restart/m-p/11682
  if softwareupdate -l | grep restart > /dev/null; then
    if [ ! -f "$HOME/.zshrc" ] || ! cat "$HOME/.zshrc" | grep '# TEMPORARY FOR INSTALL DOCTOR MACOS' > /dev/null; then
      echo 'bash <(curl -sSL https://install.doctor/start) # TEMPORARY FOR INSTALL DOCTOR MACOS' >> "$HOME/.zshrc"
    fi
    logg info 'Reboot required - shutting down immediately' && sudo shutdown -r now
    # TODO - Automatically log in after reboot
  fi
  if command -v gsed > /dev/null; then
    sudo gsed -i '/# TEMPORARY FOR INSTALL DOCTOR MACOS/d' "$HOME/.zshrc" || logg warn "Failed to remove kickstart script from .zshrc"
  else
    sudo sed -i '/# TEMPORARY FOR INSTALL DOCTOR MACOS/d' "$HOME/.zshrc" || logg warn "Failed to remove kickstart script from .zshrc"
  fi
fi

### Ensure dependencies are installed on Linux
if ! command -v curl > /dev/null || ! command -v git > /dev/null || ! command -v expect > /dev/null || ! command -v rsync > /dev/null; then
    if command -v apt-get > /dev/null; then
        # @description Ensure `build-essential`, `curl`, `expect`, `git`, `rsync`, `procps`, and `file` are installed on Debian / Ubuntu
        sudo apt-get update
        sudo apt-get install -y build-essential curl expect git rsync procps file
    elif command -v dnf > /dev/null; then
        # @description Ensure `curl`, `expect`, `git`, `rsync`, `procps-ng`, and `file` are installed on Fedora (as well as the Development Tools package)
        sudo dnf groupinstall -y 'Development Tools'
        sudo dnf install -y curl expect git rsync procps-ng file
    elif command -v yum > /dev/null; then
        # @description Ensure `curl`, `expect`, `git`, `rsync`, `procps-ng`, and `file` are installed on CentOS (as well as the Development Tools package)
        sudo yum groupinstall -y 'Development Tools'
        sudo yum install -y curl expect git rsync procps-ng file
    elif command -v pacman > /dev/null; then
        # @description Ensure `base-devel`, `curl`, `expect`, `git`, `rsync`, `procps-ng`, and `file` are installed on Archlinux
        sudo pacman update
        sudo pacman -Sy base-devel curl expect git rsync procps-ng file
    elif command -v zypper > /dev/null; then
        # @description Ensure `curl`, `expect`, `git`, `rsync`, `procps`, and `file` are installed on OpenSUSE (as well as the devel_basis pattern)
        sudo zypper install -yt pattern devel_basis
        sudo zypper install -y curl expect git rsync procps file
    elif command -v apk > /dev/null; then
        # @description Ensure `curl`, `expect`, `git`, `rsync`, `procps`, and `file` are installed on Alpine
        apk add build-base curl expect git rsync procps file
    elif [ -d /Applications ] && [ -d /Library ]; then
        # @description Ensure CLI developer tools are available on macOS (via `xcode-select`)
        sudo xcode-select -p >/dev/null 2>&1 || xcode-select --install
    elif [[ "$OSTYPE" == 'cygwin' ]] || [[ "$OSTYPE" == 'msys' ]] || [[ "$OSTYPE" == 'win32' ]]; then
        # @description Ensure `curl`, `expect`, `git`, and `rsync` are installed on Windows
        choco install -y curl expect git rsync
    fi
fi

### Ensure Linux Homebrew is loaded
loadLinuxbrew() {
  if ! command -v brew > /dev/null; then
    if [ -d "$HOME/.linuxbrew" ]; then
      eval "$("$HOME/.linuxbrew/bin/brew" shellenv)"
    elif [ -d "/home/linuxbrew/.linuxbrew" ]; then
      eval "(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
    fi
  fi
}

### Ensures Homebrew folders have proper owners / permissions
fixHomebrewPermissions() {
  if command -v brew > /dev/null; then
    logg info 'Applying proper permissions on Homebrew folders'
    sudo chmod -R go-w "$(brew --prefix)/share"
    BREW_DIRS="share/man share/doc share/zsh/site-functions etc/bash_completion.d"
    for BREW_DIR in $BREW_DIRS; do
      if [ -d "$(brew --prefix)/$BREW_DIR" ]; then
        sudo chown -R "$(whoami)" "$(brew --prefix)/$BREW_DIR"
      fi
    done
    brew update --force --quiet
  fi
}

### Installs Homebrew
ensurePackageManagerHomebrew() {
  if ! command -v brew > /dev/null; then
    if command -v sudo > /dev/null && sudo -n true; then
      echo | bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    else
      logg info 'Homebrew is not installed. Password may be required.'
      bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" || BREW_EXIT_CODE="$?"
      if [ -n "$BREW_EXIT_CODE" ]; then
        logg warn 'Homebrew was installed but part of the installation failed to complete successfully.'
        fixHomebrewPermissions
      fi
    fi
  fi
}

### Logic
loadLinuxbrew
ensurePackageManagerHomebrew
loadLinuxbrew

### Enable auto-update service
if [ -d /Applications ] && [ -d System ]; then
  # Enable Homebrew auto-update service if system is macOS
  if brew autoupdate status | grep 'Autoupdate is not configured.' > /dev/null; then
    logg info 'Enabling Homebrew auto-update service (every 24 hours)'
    brew autoupdate start --cleanup --greedy --upgrade
  fi
fi

### Scrub ~/.viminfo
if [ -f "$HOME/.viminfo" ]; then
  logg info 'Removing ~/.viminfo' && sudo rm -f "$HOME/.vimino"
fi
{{ end -}}
