#! /usr/bin/env bash
set -e

# Settings
PACKAGE_LIST_CMD="brew list"
PACKAGE_INSTALL_CMD="brew install"

#
# Package list
#

CORE_PKGS=(
  "aspell --with-lang-en --with-lang-el --with-lang-sv"
  "global --with-ctags --with-pygments"
  ack
  ansible
  bash
  bazaar
  colordiff
  ctop
  dep
  dpkg
  geckodriver
  git
  git-crypt
  git-standup
  go
  goreleaser/tap/goreleaser
  heroku
  htop
  httpie
  jq
  kubernetes-cli
  kubernetes-helm
  less
  lua
  luarocks
  mysql
  openshift-cli
  peco
  pyenv
  rbenv
  rclone
  readline
  reattach-to-user-namespace
  redis
  ruby-build
  shellcheck
  source-highlight
  sshfs
  the_silver_searcher
  tmux
  tree
  watch
  wget
  yank
  yarn
  zsh
)

PERSONAL_PKGS=(
  "mkvtoolnix --with-qt"
)

#
# Main
#

main() {
  cache_installed_packages

  install_packages "core" "${CORE_PKGS[@]}"

  if [[ " $* " == *" personal "* ]]; then
    install_packages "personal" "${PERSONAL_PKGS[@]}"
  fi
}

#
# The rest...
#

INSTALLED_PACKAGES=()

package_name() {
  local install_args="$1"
  local pkg

  pkg="$(echo "$install_args" | awk '{ print $1 }')"
  [[ "$pkg" == *'/'* ]] && pkg="$(basename "$pkg")"

  echo "$pkg"
}

cache_installed_packages() {
  if [ ${#INSTALLED_PACKAGES[@]} -eq 0 ]; then
    echo "--> Getting list of installed packages"
    mapfile -t INSTALLED_PACKAGES < <($PACKAGE_LIST_CMD)
  fi
}

is_package_installed() {
  local pkg="$1"
  cache_installed_packages

  for i in "${INSTALLED_PACKAGES[@]}"; do
    [[ "$pkg" == "$i" ]] && return 0
  done
  return 1
}

install_package() {
  $PACKAGE_INSTALL_CMD "$@"
}

install_packages() {
  local group="$1"
  local pkg
  shift 1

  echo "--> Group: ${group}"
  for install_args in "$@"; do
    pkg="$(package_name "$install_args")"

    if is_package_installed "$pkg"; then
      echo "    Exists: ${pkg}"
    else
      echo "    Installing: ${pkg}"
      install_package "$install_args"
    fi
  done
}

main "$@"
