#!/bin/bash

last=`cat /tmp/lastdesk`

namelast=$last
namecurrent=`bspc query -d focused -D --names`
wincurrent=`bspc query -d focused -N`

if [[ "$last" -gt "1" ]]; then
  del_desks=0

  for desk in `seq 1 $last`; do
    if [[ -z `bspc query -N -d "$desk"` ]]; then
      let "del_desks += 1"
      bspc desktop "$desk" -r
    else
      let "newname = desk - del_desks"
      bspc desktop "$desk" -n "$newname"
    fi
  done

  let "last = last - del_desks"
  echo "$last"

  # Always keep desktop 1 existing, even if empty
  if [[ "$last" -eq "0" ]]; then
    bspc monitor -a 1
    bspc desktop -f 1
    last=1
  # Allow for an additional empty desktop
  elif [[ "$namecurrent" -eq "$namelast" && -z "$wincurrent" ]]; then
    let "last=$last + 1"
    bspc monitor -a "$last"
    bspc desktop -f "$last"
  fi
fi

echo "$last" > /tmp/lastdesk
