#!/bin/sh
URL="http://localhost:8080"
FULL=""
if command -v curl >/dev/null 2>&1; then
    tries=0
    while [ "$tries" -lt 60 ] && ! curl -fs -o /dev/null --max-time 2 "$URL/login"; do
        tries=$((tries + 1))
        sleep 1
    done
    if [ "$1" != "--window" ] && curl -fs --max-time 3 "$URL/screen.json" 2>/dev/null | grep -q '"full_screen": *true'; then
        FULL="--kiosk"
    fi
else
    sleep 5
fi
if [ -n "$FULL" ] && command -v wlr-randr >/dev/null 2>&1; then
    wlr-randr 2>/dev/null | awk '
        /^[^ ]/ { name = $1 }
        / px, .*current/ { split($1, size, "x"); if (size[1] + 0 >= 3840) big[name] = 1 }
        /^ +1920x1080 px,/ { ok[name] = 1 }
        END { for (name in big) if (ok[name]) print name }' |
    while read -r output; do
        wlr-randr --output "$output" --mode 1920x1080 >/dev/null 2>&1 || true
    done
fi
PROFILE="${XDG_CONFIG_HOME:-$HOME/.config}/bagcam-screen"
for browser in chromium chromium-browser; do
    if command -v "$browser" >/dev/null 2>&1; then
        if [ -n "$FULL" ]; then
            exec "$browser" "$URL" --kiosk --user-data-dir="$PROFILE" --start-maximized \
                --no-first-run --no-default-browser-check --noerrdialogs --disable-infobars \
                --enable-features=OverlayScrollbar --disable-session-crashed-bubble --hide-crash-restore-bubble \
                --touch-events=enabled --password-store=basic --check-for-update-interval=31536000
        fi
        exec "$browser" --user-data-dir="$PROFILE" --app="$URL" --start-maximized \
            --no-first-run --no-default-browser-check --noerrdialogs --disable-infobars \
            --disable-session-crashed-bubble --password-store=basic --check-for-update-interval=31536000
    fi
done
exec xdg-open "$URL"
