#!/usr/bin/env perl

use strict;
use warnings;
use constant OS	=> `uname | tr -d '\n'`;
use constant {
	SLOCK_PATH			=> 'slock',
	XSCREENSAVER_PATH	=> 'xscreensaver-command',
	ACPI_PATH			=> '/usr/sbin/acpiconf',
	KILL_PATH			=> '/usr/bin/killall',
	SHUTDOWN_PATH		=> '/sbin/shutdown',
	LOGINCTL_PATH		=> '/usr/bin/loginctl',
	NOTIF_PATH			=> 'notify-send',
	EMACS_PATH			=> 'emacsclient'
};
use constant LIST => [
	'Lock screen',
	'Sleep',
	'Logout',
	'Reboot',
	'Shutdown'
	];
use constant CONFIRM => [
	"No",
	"Yes"
	];

sub confirm
{
	my ($var) = @_;
	my $list;
	my $choice;

	for (@{+CONFIRM}) {
		$list .= $_ . "\n";
	}
	$choice = `printf "%s" "$list" | dmenu -i -p "$var?" -l 2 -m 0`;
	chomp $choice;
	if ($choice eq ${+CONFIRM}[1]) {
		return (1);
	}
	return (0);
}

sub action
{
	my ($var) = @_;
	my $pid;

	chomp $var;
	if ($var eq ${+LIST}[0]) {
		exec(XSCREENSAVER_PATH, '-lock');
	}
	elsif ($var eq ${+LIST}[1]) {
		$pid = fork();
		if (not $pid) {
			exec(XSCREENSAVER_PATH, '-lock');
		}
		else {
			system(
				NOTIF_PATH,
				'-u',
				'normal',
				'shutdown',
				'  G\'night, partner!'
			);
			sleep 2;
			if (OS eq 'Linux') {
				exec('systemctl', 'suspend');
			}
			exec(ACPI_PATH, '-s', '3');
		}
	}
	elsif ($var eq ${+LIST}[2]) {
		if (confirm($var) == 1) {
			system(EMACS_PATH, '-e', '"(save-buffers-kill-terminal)"');
			if (OS eq 'Linux') {
				exec(LOGINCTL_PATH, 'terminate-session', 'self');
			}
			exec(KILL_PATH, 'dwm');
		}
	}
	elsif ($var eq ${+LIST}[3]) {
		if (confirm($var) == 1) {
			system(EMACS_PATH, '-e', '"(save-buffers-kill-terminal)"');
			if (OS eq 'Linux') {
				exec('systemctl', 'reboot');
			}
			system(
				NOTIF_PATH,
				'-u',
				'normal',
				'shutdown',
				'  Rebootin\', partner!'
				);
			exec(SHUTDOWN_PATH, '-r', 'now');
		}
	}
	elsif ($var eq ${+LIST}[4]) {
		if (confirm($var) == 1) {
			system(EMACS_PATH, '-e', '"(save-buffers-kill-terminal)"');
			system(
				NOTIF_PATH,
				'-u',
				'normal',
				'shutdown',
				'  Farewell, partner!'
				);
			sleep 2;
			if (OS eq 'Linux') {
				exec('systemctl', 'poweroff');
			}
			exec(SHUTDOWN_PATH, '-p', 'now');
		}
	}
	return;
}

sub main
{
	my $list;
	my $choice;

	for (@{+LIST}) {
		$list .= $_ . "\n";
	}
	$choice = `printf "%s" "$list" | dmenu -i -l 5 -m 0`;
	action($choice);
	return (0);
}

main();

__END__