#!/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=()
if current_name="$("${TOOL}" list-workspaces --fields local_name --focused-only)"; then
  mesg[1]='-mesg'
  mesg[2]="$(printf '<span alpha="50%%">Current name: "%s"</span>' "${current_name}")"
fi
if new_name="$(rofi -dmenu -p 'New workspace name' -lines 0 -width 30 "${mesg[@]}")"; then
  "${TOOL}" rename-workspace "${new_name}"
else
  exit $?
fi
