github.com/rigado/snapd@v2.42.5-go-mod+incompatible/overlord/configstate/configcore/powerbtn.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2017 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package configcore 21 22 import ( 23 "fmt" 24 "os" 25 "path/filepath" 26 27 "github.com/snapcore/snapd/dirs" 28 "github.com/snapcore/snapd/osutil" 29 "github.com/snapcore/snapd/overlord/configstate/config" 30 ) 31 32 func init() { 33 supportedConfigurations["core.system.power-key-action"] = true 34 } 35 36 func powerBtnCfg() string { 37 return filepath.Join(dirs.GlobalRootDir, "/etc/systemd/logind.conf.d/00-snap-core.conf") 38 } 39 40 // switchHandlePowerKey changes the behavior when the power key is pressed 41 func switchHandlePowerKey(action string) error { 42 validActions := map[string]bool{ 43 "ignore": true, 44 "poweroff": true, 45 "reboot": true, 46 "halt": true, 47 "kexec": true, 48 "suspend": true, 49 "hibernate": true, 50 "hybrid-sleep": true, 51 "lock": true, 52 } 53 54 cfgDir := filepath.Dir(powerBtnCfg()) 55 if !osutil.IsDirectory(cfgDir) { 56 if err := os.MkdirAll(cfgDir, 0755); err != nil { 57 return err 58 } 59 } 60 if !validActions[action] { 61 return fmt.Errorf("invalid action %q supplied for system.power-key-action option", action) 62 } 63 64 content := fmt.Sprintf(`[Login] 65 HandlePowerKey=%s 66 `, action) 67 return osutil.AtomicWriteFile(powerBtnCfg(), []byte(content), 0644, 0) 68 } 69 70 func handlePowerButtonConfiguration(tr config.Conf) error { 71 output, err := coreCfg(tr, "system.power-key-action") 72 if err != nil { 73 return err 74 } 75 if output == "" { 76 if err := os.Remove(powerBtnCfg()); err != nil && !os.IsNotExist(err) { 77 return err 78 } 79 80 } else { 81 if err := switchHandlePowerKey(output); err != nil { 82 return err 83 } 84 } 85 return nil 86 }