#!/usr/bin/env bash

# Current Theme
dir="$HOME/.config/rofi/powermenu/type-1"
theme='style-1'

# CMDs
uptime="`uptime -p | sed -e 's/up //g'`"
host=`hostnamectl hostname`

# Options
shutdown='  Shutdown'
reboot='󰜉  Reboot'
lock='󰌾  Lock'
suspend='󰤄  Suspend'
logout='󰗼  Logout'
yes='  Yes'
no='  No'

# Rofi CMD
rofi_cmd() {
	rofi -dmenu \
		-p "$host" \
		-mesg "Uptime: $uptime" \
		-theme ${dir}/${theme}.rasi \
		-theme-str 'mainbox {children: ["prompt", "message", "listview" ];}' \
		-theme-str 'listview {columns: 1; lines: 1;}' \
		-theme-str 'element-text {horizontal-align: 0.5;}' \
		-theme-str 'textbox {horizontal-align: 0.5;}'
}

# Confirmation CMD
confirm_cmd() {
	rofi -theme-str 'window {location: center; anchor: center; fullscreen: false; width: 250px;}' \
		-theme-str 'mainbox {children: [ "message", "listview" ];}' \
		-theme-str 'listview {columns: 2; lines: 1;}' \
		-theme-str 'element-text {horizontal-align: 0.5;}' \
		-theme-str 'textbox {horizontal-align: 0.5;}' \
		-dmenu \
		-p 'Confirmation' \
		-mesg 'Are you Sure?' \
		-theme ${dir}/${theme}.rasi
}

# Ask for confirmation
confirm_exit() {
	echo -e "$yes\n$no" | confirm_cmd
}

# Pass variables to rofi dmenu
run_rofi() {
	local option="$1"
	case "$option" in
		--shutdown)
			echo -e "$shutdown" | rofi_cmd
			;;
		--reboot)
			echo -e "$reboot" | rofi_cmd
			;;
		--lock)
			echo -e "$lock" | rofi_cmd
			;;
		--suspend)
			echo -e "$suspend" | rofi_cmd
			;;
		--logout)
			echo -e "$logout" | rofi_cmd
			;;
		*)
			echo "Invalid option"
			exit 1
			;;
	esac
}

# Execute Command
run_cmd() {
	selected="$(confirm_exit)"
	if [[ "$selected" == "$yes" ]]; then
		if [[ $1 == '--shutdown' ]]; then
			systemctl poweroff -i
		elif [[ $1 == '--reboot' ]]; then
			systemctl reboot
		elif [[ $1 == '--suspend' ]]; then
			systemctl suspend
		elif [[ $1 == '--logout' ]]; then
			hyprctl dispatch exit || pkill -u mgtn wayfire || niri msg action quit
		elif [[ $1 == '--lock' ]]; then
			$(hyprlock)
		fi
	else
		exit 0
	fi
}

# Actions
option="$1"
chosen="$(run_rofi $option)"
case ${chosen} in
    $shutdown)
		run_cmd --shutdown
        ;;
    $reboot)
		run_cmd --reboot
        ;;
    $lock)
		run_cmd --lock
        ;;
    $suspend)
		run_cmd --suspend
        ;;
    $logout)
		run_cmd --logout
        ;;
esac
