#!/usr/bin/env bash

# See https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -o errexit -o errtrace -o nounset -o pipefail

readonly HELP_HEADING='Select a workspace group to activate.'
readonly HELP_CONTENT='You can create a new group by typing a new name.
Note that the default group is shown as &lt;default>.'
readonly HELP_FORMAT='<span alpha="50%%" size="smaller"><b>%s</b>
<i>%s</i></span>'
# shellcheck disable=SC2059
# shellcheck disable=SC2155
readonly HELP_TEXT="$(printf "${HELP_FORMAT}" "${HELP_HEADING}" \
  "${HELP_CONTENT}")"

command_exists() {
  type "$1" &> /dev/null
}

get_tool() {
  filename="$1"
  local dir tool
  dir="$(cd -- "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
  tool="${dir}/${filename}"
  command_exists "${tool}" || tool="${filename}"
  printf '%s\n' "${tool}"
}

main() {
  select_groups="$(get_tool i3-select-workspace-group)"
  if ! group="$("${select_groups}" -mesg "${HELP_TEXT}")"; then
    exit 1
  fi
  local tool
  tool="$(get_tool "${I3_WORKSPACE_GROUPS_CLI:-i3-workspace-groups}")"
  "${tool}" "$@" switch-active-group "${group}"
}

main "$@"
