#!/bin/sh

# This configuration file describes a minimal example for a Catacomb config.
#
# The following applications should be installed or replaced:
# - tremor: Used for vibration effects (https://github.com/catacombing/tremor)
# - epitaph: Panel (https://github.com/catacombing/epitaph)
# - tzompantli: Application launcher (https://github.com/catacombing/tzompantli)
# - squeekboard: Virtual Keyboard (https://gitlab.gnome.org/World/Phosh/squeekboard)
# - swayidle: Automatic idle timeouts (https://github.com/swaywm/sway)
# - grim: Screenshots (https://gitlab.freedesktop.org/emersion/grim)
# - slurp: Screenshot region selection (https://github.com/emersion/slurp)

# Exit on error
set -e

# Key Bindings

## Ignore power-button press, to allow binding to it
systemd-inhibit --what handle-power-key sleep infinity &

## Launch `tzompantli` when holding the power button
catacomb msg bind-key --trigger press '*' XF86PowerOff bash -c \
    "sleep 0 0 0 0 0 0 0 0.5 && \
        if [ \"\$(catacomb msg dpms)\" == \"on\" ]; then \
            (tremor 150 0 1; tzompantli) \
        fi"

## Turn off display when pressing the power button
catacomb msg bind-key --trigger release '*' XF86PowerOff bash -c \
    "if pkill -SIGINT -xf \"sleep 0 0 0 0 0 0 0 0.5\"; then \
        if [ \"\$(catacomb msg dpms)\" == \"on\" ]; then \
            catacomb msg dpms off; \
        else \
            catacomb msg dpms on; \
        fi \
    fi"

## Take a screenshot on `power + volume down` and save it to /tmp/screenshot.png
catacomb msg bind-key --trigger press '*' XF86PowerOff+XF86AudioLowerVolume bash -c \
    "pkill -SIGINT -xf \"sleep 0 0 0 0 0 0 0 0.5\"; \
    tremor 150 0 1; \
    geometry=\$(slurp 2>&1); \
    if [[ \$geometry == \"selection cancelled\" ]]; then \
        grim /tmp/screenshot.png; \
    else \
        grim -g \"\$geometry\" /tmp/screenshot.png; \
    fi"

## Allow manually toggling the virtual keyboard
catacomb msg bind-key '*' EnableVirtualKeyboard \
    busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b true
catacomb msg bind-key '*' AutoVirtualKeyboard \
    busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b false

## Bind global volume keys
catacomb msg bind-key --trigger repeat '*' XF86AudioRaiseVolume \
    pactl set-sink-volume 0 +5%
catacomb msg bind-key --trigger repeat '*' XF86AudioLowerVolume \
    pactl set-sink-volume 0 -5%

# Ensure the virtual keyboard is enabled
gsettings set org.gnome.desktop.a11y.applications screen-keyboard-enabled true

# Spawn background apps
squeekboard &
epitaph &

# Turn off display after 3 minutes, suspend 30s later
swayidle -w \
    timeout 180 'catacomb msg dpms off' \
        resume 'catacomb msg dpms on' \
    timeout 210 'systemctl suspend' \
        after-resume 'catacomb msg dpms on' &

# Wait for completion
wait
