#!/bin/sh

awk -F ',' \
	-v sq="'" \
	-v printfSn="printf %s\\\\n " \
	-v rofiTheme='
element { font: "Noto Mono 11"; }
' '
function endBlock() {
	if(blockState == 0) {
		return
	}
	if(blockState == 1) {
		print "Warning: " name " has no body and will not be ignored"
		return
	}

	print name "() {"
	print body
	print "}"
	i=f++
	funcs[i]["name"] = name
	funcs[i]["icon"] = icon
	funcs[i]["shortcut"] = shortcut
	funcs[i]["label"] = label
	
	body=""
	bindLinesCount=0
	blockState=0
}

BEGIN {
	print "#!/bin/sh"
	print "export SCHEME=\"$(xrescat basilisk.theme)\""
	print "export BAS_ROOT=\"$(dirname \"$(realpath \"$0\")\")/../\""
	shortcutLen=0
	blockState=0
	bindLinesCount=0
}
/^[\t ]*#/ || length($0) == 0 { next }
/^[^\t ].*/ {
	if(blockState > 1) {
		endBlock()
	}
	sub(/^[ \t]+/, "");
	sub(/[ \t]+$/, "");
	name=$1
	shortcut=$2
	l = length(shortcut)
	if(l > shortcutLen) {
		shortcutLen = l
	}
	label=$3
	icon=$4
	body=""
	blockState=1
	next
}
/^[\t ]+/ && blockState > 0 {
	blockState=2
	sub(/^[ \t]+/, "");
	sub(/[ \t]+$/, "");
	body=body $0 "\n"
	next
}

function printRofiBlock() {
	printf "%s", "printf %s\\\\n " sq
	f=0
	for(i in funcs) {
		if(f!=0) {
			print ""
		}
		f=1
		printf "%" shortcutLen "s", funcs[i]["shortcut"]
		printf "%s", ". " funcs[i]["label"]
	}
	printf "%s", sq "| rofi_report"
}
function printMenuBlock() {
	printf "%s", "case \"$("
	printRofiBlock()
	print ")\" in"
	for(i in funcs) {
		print i ") " funcs[i]["name"] " ;;"
	}
	print "esac"
}
function printCallBlock() {
	print "case \"$1\" in"
	for(i in funcs) {
		print "\"" funcs[i]["name"] "\") " funcs[i]["name"] " ;;"
	}
	for(i in funcs) {
		print "\"" funcs[i]["shortcut"] "\") " funcs[i]["name"] " ;;"
	}
	print "esac"
}
END {
	endBlock()
	print "rofi_report() {"
	print "[ -n \"$BASILISK_ROFI_REPORT_STATE\" ] && printf %s\\n "open" >> \"$BASILISK_ROFI_REPORT_STATE\""
	print "rofi -dmenu -format i -matching prefix -auto-select -markup -theme-str " sq rofiTheme sq " $BASILISK_ROFI_ARGS"
	print "[ -n \"$BASILISK_ROFI_REPORT_STATE\" ] && printf %s\\n "closed" >> \"$BASILISK_ROFI_REPORT_STATE\""
	print "}"
	print "if [ -z \"$1\" ]; then"
	printMenuBlock()
	print "else"
	printCallBlock()
	print "fi"
}' "$(dirname "$0")/components" > "$(dirname "$0")/bin/bas"
chmod +x "$(dirname "$0")/bin/bas"
