#!/bin/bash
#
#
# rofi-bang
#

# Allows execution of arbitrary commands through rofi by
# invoking shell scripts. These shell scripts can in turn
# of course be other rofi commands, which allows the creation
# of chained rofi executions (e.g. !c 1+2) to run a
# calculator script within rofi and immediately execute it.
# Hence, rofi-bang.

cwd="$XDG_CONFIG_HOME"/rofi
if [ ! -d "$cwd" ]; then
	echo "The necessary directory at $HOME/.config/rofi is not set up correctly."
	exit 1
fi

cmdfile="$cwd/rofi-bang-commands.csv"
if [ ! -f "$cmdfile" ]; then
	echo "The nessesary file at $cwd/rofi-bang-commands.csv has not been found."
	exit 1
fi

# Present the initial selection screen - but as soon as only one candidate is left exit out
# since bangs are unique (!text will not be matched by anything else) it should automatically exit
# whenever a bang has been typed
selection=$(
	cut <"$cmdfile" -s -d ',' -f 1,2 |
		sed 's/,/:   /' |
		printf "%s\n%s\n%s" "$(cat -)" "suffix that is not in cmd file" "one last entry" |
		rofi -dmenu -i -p "Run> " -theme "Arc-Dark" -auto-select |
		sed 's/:   /,/' |
		head -n 1
)
# we did not select anything, just exit
if [ -z "$selection" ]; then exit 0; fi

# we selected something, check if it is in the bang commands file
# if it is, we should execute the bang
is_bang=$(grep "$selection" "$cmdfile")
if [ -n "$is_bang" ]; then
	cmd=$(echo "$is_bang" | cut -s -d ',' -f 4)
	echo "$cmd" | xargs --no-run-if-empty -I "{}" /bin/bash -c "{}"
else
	echo "not implemented yet, should re-run rofi with the exact same settings"
fi