#! /usr/bin/env bash

# Defines verification/validation functions.

# Label: Verify App Store Applications
# Description: Check for missing App Store applications.
verify_app_store_applications() {
  local applications=""

  printf "\n%s\n" "Checking App Store applications..."
  applications="$(mas list)"

  while read line; do
    if [[ "$line" == "mas install"* ]]; then
      application=$(printf "$line" | awk '{print $3}')
      verify_listed_application "$application" "${applications[*]}"
    fi
  done < "$MAC_OS_PATH/bin/install_app_store"

  printf "%s\n" "App Store check complete."
}
export -f verify_app_store_applications

# Label: Verify Homebrew Casks
# Description: Check for missing Homebrew casks.
verify_homebrew_casks() {
  local applications=""

  printf "\nChecking Homebrew casks...\n"

  applications="$(brew list --casks)"

  while read line; do
    if [[ "$line" == "brew install --cask"* ]]; then
      application=$(printf "%s" "$line" | awk '{print $5}')
      verify_listed_application "$application" "${applications[*]}"
    fi
  done < "$MAC_OS_PATH/bin/install_homebrew_casks"

  printf "%s\n" "Homebrew cask check complete."
}
export -f verify_homebrew_casks

# Label: Verify Homebrew Formulas
# Description: Check for missing Homebrew formulas.
verify_homebrew_formulas() {
  local applications=""

  printf "Checking Homebrew formulas...\n"

  applications="$(brew list --formulae)"

  while read line; do
    if [[ "$line" == "brew install"* ]]; then
      application=$(printf "%s" "$line" | awk '{print $3}')

      # Exception: "gpg" is the binary but is listed as "gnugp".
      if [[ "$application" == "gpg" ]]; then
        application="gnupg"
      fi

      verify_listed_application "$application" "${applications[*]}"
    fi
  done < "$MAC_OS_PATH/bin/install_homebrew_formulas"

  printf "%s\n" "Homebrew formula check complete."
}
export -f verify_homebrew_formulas

# Label: Verify Listed Application
# Description: Verify listed application exists.
# Parameters: $1 (required): Current application, $2 (required): Application list.
verify_listed_application() {
  local application="$1"
  local applications="$2"

  if [[ "${applications[*]}" != *"$application"* ]]; then
    printf "%s\n" " - Missing: $application"
  fi
}
export -f verify_listed_application
