#!/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 to move the focused container into'
readonly HELP_CONTENT='You can select a new (non existing) workspace by using the format "group:number", for example "work:2".
Displayed table columns: group, number, window icons, and name.'
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}")"

readonly DISPLAYED_FIELDS='group,local_number,window_icons,static_name'

ROFI_CMD=(rofi -dmenu -p 'Workspace' -theme-str 'window {width: 60ch;}'
  -mesg "${HELP_TEXT}")

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() {
  local tool
  tool="$(get_tool "${I3_WORKSPACE_GROUPS_CLI:-i3-workspace-groups}")"
  local displayed_workspaces
  mapfile -t displayed_workspaces < <(
    "${tool}" list-workspaces --fields "${DISPLAYED_FIELDS}" |
      column -t -s $'\t' -o '    '
  )
  if ! selected="$(printf '%s\n' "${displayed_workspaces[@]}" |
    "${ROFI_CMD[@]}")"; then
    exit 1
  fi
  local workspaces
  mapfile -t workspaces < <("${tool}" list-workspaces --fields 'global_name')
  for i in "${!displayed_workspaces[@]}"; do
    local line
    line="${displayed_workspaces[${i}]}"
    if [[ "${line}" == "${selected}" ]]; then
      i3-msg 'move container to workspace "'"${workspaces[${i}]}"'"'
      exit
    fi
  done
  local group local_number
  # No existing workspace was selected, assume it's a new workspace with a
  # format of "group:local_number".
  group="${selected%%:*}"
  local_number="${selected##*:}"
  "${tool}" move-to-number --group-name "${group}" "${local_number}"
}

main "$@"
