#!/bin/bash

if pkill -x wl-mirror; then
    notify-send "wl-mirror" "Mirroring stopped" -i video-display
    exit 0
fi

if command -v niri >/dev/null && niri msg outputs >/dev/null 2>&1; then
    ACTIVE_OUTPUTS=$(niri msg outputs | awk -F'[()]' '/^Output/ {print $2}')
    SOURCE_TOOL="Niri"
elif command -v wlr-randr >/dev/null; then
    ACTIVE_OUTPUTS=$(wlr-randr | awk '/^[^ ]/ {name=$1} /Enabled: yes/ {print name}')
    SOURCE_TOOL="wlr-randr"
else
    notify-send "Mirror Error" "Neither 'niri' nor 'wlr-randr' found." -u critical
    exit 1
fi

INTERNAL=""
EXTERNAL=""

for out in $ACTIVE_OUTPUTS; do
    if [[ $out == eDP* ]]; then
        INTERNAL="$out"
    else
        EXTERNAL="$out"
    fi
done

if [[ -z "$INTERNAL" ]]; then
    notify-send "Mirror Error" "Internal screen (eDP) not found." -u critical
    exit 1
fi

if [[ -z "$EXTERNAL" ]]; then
    notify-send "Mirror Status" "No external monitor detected." -u low
    exit 1
fi

notify-send "wl-mirror ($SOURCE_TOOL)" "Mirroring $INTERNAL ➔ $EXTERNAL" -i video-display

wl-mirror --fullscreen-output "$EXTERNAL" --scaling fit "$INTERNAL" || \
notify-send "Mirror Error" "Failed to start wl-mirror" -u critical
