#!/usr/bin/env bash

# Exit on error. Append "|| true" if you expect an error.
set -o errexit
# Exit on error inside any functions or subshells.
set -o errtrace
# Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR
set -o nounset
# Catch the error in case mysqldump fails (but gzip succeeds) in `mysqldump |gzip`
set -o pipefail

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

DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
TOOL="${DIR}/i3-workspace-groups"
command_exists "${TOOL}" || TOOL="i3-workspace-groups"

mesg='<span alpha="50%">Will focus on the selected workspace</span>'
if selected_index="$("${TOOL}" list-workspaces \
  --fields 'group,local_number,local_name' |
  rofi -format d -dmenu -no-custom -width 30 -p 'Workspace' \
    -mesg "${mesg}")"; then
  selected_workspace="$("${TOOL}" list-workspaces --fields 'global_name' |
    head -"${selected_index}" | tail -1)"
  i3-msg 'workspace --no-auto-back-and-forth "'"${selected_workspace}"'"'
else
  exit $?
fi
