#!/bin/sh
#
# ensure_num_desktops - create new space from keyboard without leaving cli
#
# note: key code 53 = mission control
#
# ---
# see: https://overflow.adminforge.de/exchange/apple/questions/407422/#407446

if [ "$#" -eq 0 ]; then
  printf '%s\n' "Usage: $(basename "$0") <num>"
  exit 1
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  printf '%s\n' "Usage: $(basename "$0") <num>"
  exit 0
fi

num_desktops="${1:-2}"
osascript <<END
do shell script "open -a 'Mission Control'"
delay 0.5
tell application "System Events"
    tell process "Dock"
        set spacesGroup to group "Spaces Bar" of group 1 of group 1
        set addDesktopButton to button 1 of (every button whose value of attribute "AXDescription" is "add desktop") of spacesGroup
        set desktopButtons to buttons of list 1 of spacesGroup
        repeat while length of desktopButtons < ${num_desktops}
            click addDesktopButton
            delay 0.5
            set desktopButtons to buttons of list 1 of spacesGroup
        end repeat
    end tell
end tell
delay 0.5
tell application "System Events" to key code 53
END
