stockholm/lass/3modules/power-action.nix

94 lines
2.1 KiB
Nix
Raw Normal View History

2016-06-16 20:42:14 +00:00
{ config, lib, pkgs, ... }:
with config.krebs.lib;
2016-06-16 20:42:14 +00:00
let
cfg = config.lass.power-action;
out = {
options.lass.power-action = api;
config = lib.mkIf cfg.enable imp;
2016-06-16 20:42:14 +00:00
};
api = {
enable = mkEnableOption "power-action";
user = mkOption {
type = types.user;
default = {
name = "power-action";
};
};
startAt = mkOption {
type = types.str;
default = "*:0/1";
};
plans = mkOption {
type = with types; attrsOf (submodule {
options = {
2016-06-18 19:51:45 +00:00
charging = mkOption {
type = nullOr bool;
default = null;
description = ''
check for charging status.
null = don't care
true = only if system is charging
false = only if system is discharging
'';
};
2016-06-16 20:42:14 +00:00
upperLimit = mkOption {
type = int;
};
lowerLimit = mkOption {
type = int;
};
action = mkOption {
type = path;
};
};
});
};
};
imp = {
systemd.services.power-action = {
serviceConfig = rec {
ExecStart = startScript;
User = cfg.user.name;
2016-06-16 20:42:14 +00:00
};
startAt = cfg.startAt;
};
users.users.${cfg.user.name} = {
inherit (cfg.user) name uid;
};
};
startScript = pkgs.writeDash "power-action" ''
2016-06-18 19:51:45 +00:00
set -euf
2016-06-16 20:42:14 +00:00
power="$(${powerlvl})"
2016-06-18 19:51:45 +00:00
state="$(${state})"
2016-06-16 20:42:14 +00:00
${concatStringsSep "\n" (mapAttrsToList writeRule cfg.plans)}
'';
2016-06-18 19:51:45 +00:00
charging_check = plan:
if (plan.charging == null) then "" else
if plan.charging
then ''&& [ "$state" = "true" ]''
else ''&& ! [ "$state" = "true" ]''
;
2016-06-16 20:42:14 +00:00
writeRule = _: plan:
2016-06-18 19:51:45 +00:00
"if [ $power -ge ${toString plan.lowerLimit} ] && [ $power -le ${toString plan.upperLimit} ] ${charging_check plan}; then ${plan.action}; fi";
2016-06-16 20:42:14 +00:00
powerlvl = pkgs.writeDash "powerlvl" ''
cat /sys/class/power_supply/BAT0/capacity
'';
2016-06-18 19:51:45 +00:00
state = pkgs.writeDash "state" ''
if [ "$(cat /sys/class/power_supply/BAT0/status)" = "Charging" ]
then echo "true"
else echo "false"
fi
'';
2016-06-16 20:42:14 +00:00
in out