Saturday, April 25, 2015

Remember screen brightness running Linux on MacBook

Running Sabayon Linux, with systemd, on a MacBook, the LCD backlight always resets to maximum brightness after reboot. This is an annoyance as it becomes necessary to adjust the brightness every time it is necessary to reboot the laptop.

To get the system to remember the brightness setting:
  1. Create a script that can save or restore the setting when called with a parameter.
  2. Create a (systemd) service that calls the script to save the setting on shutdown and restore the setting on startup.
Script: /usr/local/bin/my-settings.sh
#!/bin/sh
# Saves and restores settings for LCD and keyboard backlights.
if [ -z $1 ]; then
    echo "Usage: my-settings.sh [save|restore]"
fi
# Set variables:
export LCD_BRIGHTNESS="/sys/devices/virtual/backlight/apple_backlight/brightness"

# Save setting:
case $1 in
 "save")
    echo Saving settings...
    # if the settings folder does not exist, create it
    if [ ! -e /etc/my-settings ]; then
     mkdir /etc/my-settings
    fi
    # if the LCD_BRIGHTNESS file exists, then save a copy:
    if [ -e $LCD_BRIGHTNESS ]; then
     cat $LCD_BRIGHTNESS > /etc/my-settings/lcd
    fi
    ;;

 "restore")
    # if saved setting exists, if LCD_BRIGHTNESS exists, echo the contents into the system device:
    if [ -e /etc/my-settings/lcd ]; then
     if [ -e $LCD_BRIGHTNESS ]; then
      cat /etc/my-settings/lcd > $LCD_BRIGHTNESS
     fi
    fi
    ;;
esac

===============

Systemd service: /usr/lib/systemd/system/my-settings.service:

[Unit]
Description=Load/Save Keyboard & LCD backlight settings

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh -c "/usr/local/bin/my-settings.sh restore"
ExecStop=/bin/sh -c "/usr/local/bin/my-settings.sh save"

[Install]
WantedBy=multi-user.target

================

Enable the script and service:
chmod +x /usr/local/bin/my-settings.sh
systemctl enable my-settings.service
systemctl start my-settings