#!/bin/bash

set -euo pipefail

with_number=false
if test "${1:-}" = --with-number; then with_number=true; fi

cur_ws="$(swaymsg -t get_workspaces | jq '.[] | select(.focused==true)')"
cur_ws_number="$(echo "$cur_ws" | jq '.num')"

cur_ws_fullname="$(echo "$cur_ws" | jq --raw-output '.name')"
# Strip workspace number from name
if [[ $cur_ws_fullname == [0-9] ]]; then
	cur_ws_name=""
else
	cur_ws_name="${cur_ws_fullname#-}"
	cur_ws_name="${cur_ws_fullname#[0-9]:}"
	cur_ws_name="${cur_ws_name# }"
fi

if test "$with_number" = true; then
	prompt="rename and renumber workspace $cur_ws_number:"
	default="$cur_ws_fullname"
else
	prompt="rename workspace $cur_ws_number:"
	default="$cur_ws_name"
fi

newname="$(
	rofi -dmenu -p "$prompt"
)"

if test "$with_number" = true; then
	if test -z "$newname"; then
		exit 1
	fi
else
	if test -z "$newname"; then
		newname="$cur_ws_number"
	else
		newname="$cur_ws_number: $newname"
	fi
fi

echo "renaming to \`$newname\`"

swaymsg "rename workspace to \"${newname//"/\\"}\""
