#!/bin/env bash

path="$HOME/.config/bspwm/bspwmrc"
tmp=$(mktemp)
primary=$(xrandr | grep " connected" | rofi -dmenu -a | awk '{ print $1 }')
secondary=$(xrandr | grep " connected" | grep -v "^$primary" | awk '{ print $1 }')
use_secondary=$(printf 'Yes\nNo\n' | rofi -dmenu -e "Use secondary displays?" -format i)

p() {
	if [ -n "$secondary" ] && [ "$use_secondary" == 0 ]; then
		printf 'bspc monitor %s -d I II III IV\n' "$primary"
		printf 'bspc monitor %s -d %s\n' "$secondary" "$secondary"
	else
		printf 'bspc monitor %s -d I II III IV V\n' "$primary"
		bspc monitor "$secondary" -r
	fi
}

p | awk -v blockstart="# START MONITOR BLOCK" \
	-v blockend="# END MONITOR BLOCK" \
	-v sq="'" \
	-v nl="\n" '
FILENAME == "-" {
	block=block $0 nl
	next
}
!inblock { print }
inblock {
	lines[++bi] = $0
}
$0 ~ blockstart {
	inblock = 1;
	bi = 0;
	printf block
	next
}
$0 == blockend && inblock {
	inblock = 0;
	print blockend;
	next;
}
ENDFILE  {
    if(inblock) {
    	print nl blockend;
   		for(i=1;i<=bi;i++) {
   			print lines[i];
   		}
    }
}
' - "$path" > "$tmp" && mv "$tmp" "$path"
chmod +x "$path"
"$path"
