#!/bin/bash
# Capture the eww bar (and optionally the area under it) with grim, for visual
# debugging of spacing and icons.
#
# Usage:
#   bar-shot                  # right end of the bar on the focused output
#   bar-shot -o eDP-1         # pick the output
#   bar-shot -f               # full bar width
#   bar-shot -p               # bar + 300px below it, to see popups
#   bar-shot -w 900           # width of the right-end crop (default 780)
#   bar-shot -O /tmp/x.png    # output path (default /tmp/bar-shot.png)
#
# Scale factor 2 is used so glyph spacing stays readable when zoomed.

set -euo pipefail

OUT=""
FULL=0
POPUP=0
WIDTH=780
FILE=/tmp/bar-shot.png
BAR_H=30
POPUP_H=320

while getopts "o:fpw:O:h" opt; do
    case "$opt" in
        o) OUT=$OPTARG ;;
        f) FULL=1 ;;
        p) POPUP=1 ;;
        w) WIDTH=$OPTARG ;;
        O) FILE=$OPTARG ;;
        h) sed -n '2,16p' "$0"; exit 0 ;;
        *) exit 2 ;;
    esac
done

if [ -z "$OUT" ]; then
    OUT=$(swaymsg -t get_outputs -r | jq -r '.[] | select(.focused) | .name')
    [ -n "$OUT" ] || OUT=$(swaymsg -t get_outputs -r | jq -r '[.[] | select(.active)][0].name')
fi

read -r X Y W _H < <(
    swaymsg -t get_outputs -r |
        jq -r --arg o "$OUT" '.[] | select(.name == $o) | "\(.rect.x) \(.rect.y) \(.rect.width) \(.rect.height)"'
)

height=$BAR_H
[ "$POPUP" -eq 1 ] && height=$POPUP_H

if [ "$FULL" -eq 1 ]; then
    geom="$X,$Y ${W}x${height}"
else
    crop=$WIDTH
    [ "$crop" -gt "$W" ] && crop=$W
    geom="$((X + W - crop)),$Y ${crop}x${height}"
fi

grim -g "$geom" -s 2 "$FILE"
echo "$FILE  ($OUT  $geom)"
