#!/usr/bin/env perl
# nightlight -- toggle GNOME "Night Light" feature through a hotkey
use v5.20;
no warnings "experimental::smartmatch";
use Getopt::Long;
use Net::DBus;

sub GsdColor {
	Net::DBus->session
	->get_service("org.gnome.SettingsDaemon.Color")
	->get_object("/org/gnome/SettingsDaemon/Color");
}

sub get_gsetting {
	my @cmd = ("gsettings", "get", @_);
	if (open(my $fh, "-|", @cmd)) {
		chomp(my $value = <$fh>);
		close($fh);
		return $value;
	}
}

sub set_gsetting {
	my @cmd = ("gsettings", "set", @_);
	system @cmd;
}

sub get_gsd_enabled {
	get_gsetting("org.gnome.settings-daemon.plugins.color",
	             "night-light-enabled") eq "true";
}

sub get_active {
	GsdColor->Get("org.gnome.SettingsDaemon.Color",
		      "NightLightActive");
}

sub get_suspended {
	GsdColor->Get("org.gnome.SettingsDaemon.Color",
		      "DisabledUntilTomorrow");
}

sub set_gsd_enabled {
	my ($status) = @_;
	set_gsetting("org.gnome.settings-daemon.plugins.color",
	             "night-light-enabled",
	             $status ? "true" : "false");
}

sub set_suspended {
	my ($status) = @_;
	GsdColor->Set("org.gnome.SettingsDaemon.Color",
	              "DisabledUntilTomorrow",
	              Net::DBus::dbus_boolean($status));
}

my $store;
my $action;
my $osd = !(-t 0 && -t 1);

GetOptions(
	"p|store!" => \$store,
	"E|enable" => sub { $action = "enable" },
	"D|disable" => sub { $action = "disable" },
	"T|toggle" => sub { $action = "toggle" },
	"q|query" => sub { $action = "is-active" },
	"s|suspend" => sub { $action = "suspend" },
	"r|resume" => sub { $action = "resume" },
	"hotkey" => sub { $action = "poke" },
) || exit(2);

if (!$action && @ARGV) {
	$action = shift(@ARGV);
}

if (!$action) {
	$action = "query";
}

if ($action eq "query") {
	if (get_gsd_enabled()) {
		if (get_suspended()) {
			say "enabled (suspended for today)";
		} elsif (get_active()) {
			say "enabled (active)";
		} else {
			say "enabled (inactive)";
		}
	} else {
		say "disabled globally";
	}
}
elsif ($action eq "is-active") {
	if (get_gsd_enabled()) {
		if (get_suspended()) {
			exit 1;
		} elsif (get_active()) {
			exit 0;
		} else {
			exit 1;
		}
	} else {
		exit 1;
	}
}
elsif ($action eq "enable") {
	set_gsd_enabled(1);
}
elsif ($action eq "disable") {
	set_gsd_enabled(0);
}
elsif ($action eq "toggle") {
	set_gsd_enabled(!get_gsd_enabled());
}
elsif ($action ~~ ["suspend", "resume", "poke"]) {
	my $value = ($action eq "suspend") ? 1
                  : ($action eq "resume") ? 0
                  : !get_suspended();
	my $text = ($value ? "paused" : "resumed");
	my $icon = ($value ? "weather-clear" : "night-light");
	set_suspended($value);
	if ($osd) {
		system("notifysend",
		       "-r", "hotkey",
		       "-i", "$icon-symbolic",
		       "-e",
		       "Night Light",
		       "Night Light has been $text.");
	} else {
		print "Night Light has been $text.\n";
	}
}
