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

98 lines
2.2 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
2016-07-26 19:36:47 +00:00
cfg = config.krebs.power-action;
2016-06-16 20:42:14 +00:00
out = {
2016-07-26 19:36:47 +00:00
options.krebs.power-action = api;
config = lib.mkIf cfg.enable imp;
2016-06-16 20:42:14 +00:00
};
api = {
enable = mkEnableOption "power-action";
battery = mkOption {
type = types.str;
default = "BAT0";
};
2016-06-16 20:42:14 +00:00
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/${cfg.battery}/capacity
2016-06-16 20:42:14 +00:00
'';
2016-06-18 19:51:45 +00:00
state = pkgs.writeDash "state" ''
if [ "$(cat /sys/class/power_supply/${cfg.battery}/status)" = "Discharging" ]
2016-06-28 15:39:03 +00:00
then echo "false"
else echo "true"
2016-06-18 19:51:45 +00:00
fi
'';
2016-06-16 20:42:14 +00:00
in out