#!/usr/bin/env bash
# Chooses this machine's primary screen: the one the SDDM login widgets are drawn on
# and whose wallpaper becomes the login background (see sddm-sync-background).
#
# Saved per machine in ~/.local/state/dotfiles/primary-screen, outside the repo,
# so it isn't synced. The default is eDP-1 on laptops (anything with a system
# battery, same check as hypr/core/startup.lua) and DP-2 everywhere else.
#
# Usage: set-primary-screen             list the connected screens and ask
#        set-primary-screen <name>      e.g. set-primary-screen DP-1
#        set-primary-screen --if-unset [name]
#                                       install.sh / bootstrap.sh: save <name> if
#                                       given; else keep the saved screen, or save
#                                       the default if none
#        set-primary-screen --clear     forget the choice and use the default
#        set-primary-screen --print     print the screen in use (saved or default)
set -euo pipefail

file="${XDG_STATE_HOME:-$HOME/.local/state}/dotfiles/primary-screen"

default_screen() {
    if ls -d /sys/class/power_supply/BAT* >/dev/null 2>&1; then
        echo eDP-1
    else
        echo DP-2
    fi
}

# Rebuilds the login background for the new screen. Called from beside this
# script, not ~/.local/bin, because system/install.sh runs this before stow has
# linked anything; and skipped until ImageMagick is installed (bootstrap.sh runs
# the sync itself once it is).
sync_background() {
    command -v magick >/dev/null || return 0
    "$(dirname "$(readlink -f "$0")")/sddm-sync-background"
}

# Connected screens: from Hyprland if it's running, else the kernel's DRM
# connectors (card1-eDP-1 -> eDP-1), which use the same names
screens() {
    if command -v hyprctl >/dev/null && hyprctl monitors >/dev/null 2>&1; then
        hyprctl monitors | sed -n 's/^Monitor \([^ ]*\) .*/\1/p'
    else
        for status in /sys/class/drm/card*-*/status; do
            [[ "$(cat "$status")" == connected ]] || continue
            basename "$(dirname "$status")" | sed 's/^card[0-9]*-//'
        done
    fi
}

save() {
    mkdir -p "${file%/*}"
    printf '%s\n' "$1" >"$file"
    echo "Primary screen set to $1"
    sync_background
}

default="$(default_screen)"

case "${1:-}" in
    --print)
        saved="$(head -n1 "$file" 2>/dev/null || true)"
        echo "${saved:-$default}"
        ;;
    --clear)
        rm -f "$file"
        echo "Primary screen cleared; using the default ($default)"
        sync_background
        ;;
    --if-unset)
        # A name passed in (install.sh / bootstrap.sh --primary-screen) always wins
        if [[ -n "${2:-}" ]]; then
            save "$2"
        elif [[ -s "$file" ]]; then
            echo "Primary screen already set to $(cat "$file") (change with: set-primary-screen)"
        else
            save "$default"
        fi
        ;;
    "")
        mapfile -t found < <(screens)
        if (( ${#found[@]} == 0 )); then
            echo "No connected screens found; pass a name: set-primary-screen <name>" >&2
            exit 1
        fi
        echo "Connected screens (Enter for the default, $default):"
        for i in "${!found[@]}"; do
            mark=""; [[ "${found[i]}" == "$default" ]] && mark="  (default)"
            printf '  %d) %s%s\n' $((i + 1)) "${found[i]}" "$mark"
        done
        while true; do
            read -rp "Primary screen? " reply
            if [[ -z "$reply" ]]; then
                name="$default"; break
            elif [[ "$reply" =~ ^[0-9]+$ ]] && (( reply >= 1 && reply <= ${#found[@]} )); then
                name="${found[reply - 1]}"; break
            fi
        done
        save "$name"
        ;;
    -*) echo "Unknown option: $1" >&2; exit 1 ;;
    *) save "$1" ;;
esac
