#!/bin/bash
# system-sleep hook for monitor-lets-go
# Install to /usr/lib/systemd/system-sleep/monitor-lets-go
#
# Writes the portable monitor config before suspend so the compositor
# never loads a stale docked config on resume (prevents black screen).
#
# Requires: sudo (passwordless for the user's own commands)

case $1/$2 in
  pre/*)
    USER_NAME="$(logname 2>/dev/null || echo "${SUDO_USER:-$USER}")"
    USER_UID="$(id -u "$USER_NAME" 2>/dev/null || echo 1000)"

    # Extract HYPRLAND_INSTANCE_SIGNATURE from the user's systemd session
    HYPR_ENV="$(systemctl --user -M "${USER_UID}@" show-environment 2>/dev/null)"
    HYPR_INSTANCE="$(echo "$HYPR_ENV" | grep HYPRLAND_INSTANCE_SIGNATURE | cut -d= -f2)"

    if [ -n "$HYPR_INSTANCE" ] && [ -n "$USER_NAME" ]; then
      XDG_RUNTIME_DIR="/run/user/$USER_UID" \
      HYPRLAND_INSTANCE_SIGNATURE="$HYPR_INSTANCE" \
      sudo -u "$USER_NAME" \
        /home/mat/.local/bin/monitor-lets-go \
          -config /home/mat/.config/monitor-lets-go/config.yaml \
          -apply portable -no-reload
    fi
    ;;
esac
