Wren Linux

wren-linux / extras / kanshi.sh

#!/bin/bash
# Screens switch by themselves when you plug a monitor in or out (kanshi): the
# laptop alone uses its own screen, and with a monitor plugged in only the
# monitor is on. Other setups (two monitors, a desktop) match no profile, so
# sway keeps every screen on. Your ~/.config/kanshi/config is never replaced.
# Usage: bash kanshi.sh [--remove | --manual]
# summary: Monitor plugged in: only the monitor is on
# security: some
# category: computer
# status: apt:kanshi
# files: data/kanshi-config lib/sway.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../lib.sh"
if [ "${1:-}" = --manual ]; then print_manual; exit; fi
need_user
CONF=${XDG_CONFIG_HOME:-$HOME/.config}/kanshi/config

if [ "${1:-}" = --remove ]; then
    remove_snippet kanshi
    pkill -x -u "$(id -u)" kanshi 2>/dev/null || true
    apt_purge kanshi
    note "Your $CONF stays; delete it if you don't want it."
    exit
fi

say "Installing kanshi"
apt_install kanshi
if [ -e "$CONF" ]; then
    note "Your $CONF stays as it is."
else
    install -D -m 0644 "$WREN_DIR/data/kanshi-config" "$CONF"
    note "Which screen is on, in $CONF: with a monitor plugged in, only the monitor."
fi
# At login and at every reload: a reload turns every screen on again, and kanshi
# only looks when one is plugged in or out, so it starts again and puts its
# profile back (Debian's kanshi has no kanshictl to ask it). One at a time.
# shellcheck disable=SC2016  # for sway to run, not expanded here
put_snippet kanshi <<<'exec_always sh -c '\''pkill -x -u "$(id -u)" kanshi; exec kanshi'\'''
# (in a running sway: now, not only from the next login)
if [ -n "${SWAYSOCK:-}" ] && ! pgrep -x -u "$(id -u)" kanshi >/dev/null; then
    swaymsg -q exec kanshi >/dev/null 2>&1 || true
fi
note "Unplugging the monitor brings the laptop's screen back."