#!/bin/bash
# sun-vd (Hyprland): Moonlight resolution profiles for Sunshine. Same interface as sun-vd for other desktops,
# so apps.json is identical everywhere:   "prep-cmd": [{ "do": "sun-vd start 3440x1440", "undo": "sun-vd stop" }]
#
#   start WxH   add a headless output "SunVD" at WxH@60, turn the real screens off (windows move onto it), and pin
#               Sunshine's absolute pointer to it. Sunshine (capture = wlr, no output_name) then streams the only
#               screen there is.
#   stop        delete ~/.config/hypr/sun-vd.lua, remove SunVD, reload the Hyprland config (real screens and pointer
#               pin come back exactly as configured), and check every screen that was on is on again.
#   status      what's active.
#
# While streaming, the rules also live in ~/.config/hypr/sun-vd.lua, which each Hyprland config loads LAST, so a
# config reload mid-stream (a theme change does one) re-applies them instead of bringing the real screen back.
# The file applies only inside the Hyprland that was running when it was written, and only while this boot's mark
# ($XDG_RUNTIME_DIR/sun-vd.active) exists: after a power cut mid-stream the next login ignores (and removes) it,
# so the real screens are never left off with no stream screen to replace them.
#
# Sunshine runs the undo only when you QUIT the app in Moonlight; a plain disconnect (closing the window, network
# drop) never runs it, which would leave the real screens off. So start also launches a watcher: once the client
# has been gone 20 s (or never connected within 90 s, or Sunshine exits), it runs stop itself.
set -u
case "${1:-}" in -h|--help|help)                  # usage on request is not an error (lines 4-20: the commands)
    echo "sun-vd: Moonlight resolution profiles for Sunshine."; sed -n '4,20s/^# \{0,1\}//p' "$0"; exit 0 ;; esac
STATE=${XDG_STATE_HOME:-$HOME/.local/state}/sun-vd
LOG=$STATE/sun-vd.log
NAME=SunVD
RULES=$HOME/.config/hypr/sun-vd.lua     # loaded last by the Hyprland config: a reload (theme change, settings) keeps the stream screen
UNITS="app-dev.lizardbyte.app.Sunshine.service sunshine.service"   # how starchaser link may have started it
mkdir -p "$STATE"
log() { echo "$(date '+%F %T') $*" >> "$LOG"; }

export XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}
MARK=$XDG_RUNTIME_DIR/sun-vd.active      # gone after a reboot or power cut (a tmpfs), unlike the rules file
# the running Hyprland (Sunshine's environment may carry a stale signature)
for s in ${HYPRLAND_INSTANCE_SIGNATURE:-} $(ls -t "$XDG_RUNTIME_DIR/hypr" 2>/dev/null); do
    HYPRLAND_INSTANCE_SIGNATURE=$s hyprctl version >/dev/null 2>&1 && { export HYPRLAND_INSTANCE_SIGNATURE=$s; break; }
done
ev() { hyprctl eval "$1" >> "$LOG" 2>&1; }
enabled() { hyprctl monitors -j | python3 -c 'import json,sys; print(" ".join(m["name"] for m in json.load(sys.stdin)))'; }
has_vd() { hyprctl monitors all -j | python3 -c "import json,sys; sys.exit(0 if any(m['name']=='$NAME' for m in json.load(sys.stdin)) else 1)"; }

stop() {
    [ -f "$STATE/watch.pid" ] && [ "$(cat "$STATE/watch.pid")" != "$$" ] && kill "$(cat "$STATE/watch.pid")" 2>/dev/null
    rm -f "$STATE/watch.pid"
    rm -f "$RULES" "$MARK"
    # SunVD goes first, then the reload. Reloading while SunVD still existed put it back at its fallback 1920x1080 at
    # 0,0, so the real screen came back beside it (at 960,0 on a 1920-wide screen); removing SunVD then moved the
    # screen to 0,0 but left the wallpaper and the taskbar where they were, three quarters of the way across (r23).
    has_vd && hyprctl output remove "$NAME" >> "$LOG" 2>&1
    sleep 1
    hyprctl reload >> "$LOG" 2>&1          # config monitor rules + device pins back; SunVD rules gone with the file
    sleep 1
    has_vd && { hyprctl output remove "$NAME" >> "$LOG" 2>&1; sleep 1; }   # (not removable while it was the only screen)
    local want missing=""
    want=$(cat "$STATE/real" 2>/dev/null)
    for m in $want; do enabled | tr ' ' '\n' | grep -qx "$m" || missing="$missing $m"; done
    for m in $missing; do ev "hl.monitor({ output = \"$m\", mode = \"preferred\", position = \"auto\", scale = \"auto\" })"; done
    # the real screens may have been powered off (screen-off timer) before or during the stream, and the "wake up"
    # then only reached SunVD: power them on with the rest of the restore
    hyprctl dispatch 'hl.dsp.dpms({ action = "enable" })' >> "$LOG" 2>&1
    rm -f "$STATE/active" "$STATE/real"
    log "stopped; on: $(enabled)${missing:+ (re-enabled by hand:$missing)}"
}

# Sunshine's client lines since the stream started: from the journal of the user unit it runs under, else (started
# by hand or by starchaser link without a unit) from its own log file, past the size it had at start
SUNLOG=${XDG_CONFIG_HOME:-$HOME/.config}/sunshine/sunshine.log
client_lines() {
    local since=$1 from=$2 u
    for u in $UNITS; do
        if systemctl --user -q is-active "$u" 2>/dev/null; then
            journalctl --user -u "$u" --since "@$since" -o cat --no-pager -q 2>/dev/null; return
        fi
    done
    [ -f "$SUNLOG" ] || return
    # a Sunshine restarted meanwhile starts its log over: then read it from the top
    [ "$(stat -c %s "$SUNLOG")" -lt "$from" ] && from=0
    tail -c +"$((from + 1))" "$SUNLOG"
}

watch() {           # runs detached from start
    echo $$ > "$STATE/watch.pid"
    local since=$1 from=${2:-0} seen=0 gone_at=0 now line
    while sleep 5; do
        [ -f "$STATE/active" ] || exit 0                                  # stopped by Sunshine's undo
        now=$(date +%s)
        pgrep -x sunshine >/dev/null || { log "watch: Sunshine exited"; stop; exit 0; }
        line=$(client_lines "$since" "$from" | grep -E "CLIENT (CONNECTED|DISCONNECTED)" | tail -1)
        case "$line" in
            *"CLIENT CONNECTED"*)    seen=1; gone_at=0 ;;
            *"CLIENT DISCONNECTED"*) seen=1; [ $gone_at = 0 ] && gone_at=$now ;;
        esac
        if [ $seen = 0 ] && [ $((now - since)) -ge 90 ]; then log "watch: no client within 90 s"; stop; exit 0; fi
        if [ $gone_at != 0 ] && [ $((now - gone_at)) -ge 20 ]; then log "watch: client gone 20 s"; stop; exit 0; fi
    done
}

case "${1:-}" in
    start)
        res=${2:-}
        [[ $res =~ ^[0-9]+x[0-9]+$ ]] || { echo "sun-vd: wrong arguments for 'start': it needs a size like 1920x1080. Run 'sun-vd --help' for more help." >&2; exit 2; }
        [ -f "$STATE/active" ] && stop
        enabled > "$STATE/real"
        hyprctl output create headless "$NAME" >> "$LOG" 2>&1
        for i in $(seq 1 20); do has_vd && break; sleep 0.25; done
        has_vd || { log "FAILED: $NAME never appeared"; exit 1; }
        code="hl.monitor({ output = \"$NAME\", mode = \"$res@60\", position = \"0x0\", scale = 1 })"
        for m in $(cat "$STATE/real"); do code="$code; hl.monitor({ output = \"$m\", disabled = true })"; done
        code="$code; hl.device({ name = \"mouse-passthrough-(absolute)\", output = \"$NAME\" })"
        touch "$MARK"
        {
            printf -- '-- written by sun-vd while a Moonlight resolution profile is streaming; removed by "sun-vd stop"\n'
            printf -- '-- only for the Hyprland running then, and only this boot (after a power cut the real screens stay on)\n'
            printf 'local f = io.open("%s", "r")\n' "$MARK"
            printf 'if not f or os.getenv("HYPRLAND_INSTANCE_SIGNATURE") ~= "%s" then\n' "$HYPRLAND_INSTANCE_SIGNATURE"
            printf '    if f then f:close() end\n    os.remove("%s")\n    return\nend\nf:close()\n' "$RULES"
            echo "$code" | sed 's/; /\n/g'
        } > "$RULES"
        ev "$code"
        # Hyprland applies the screen changes a moment later; Sunshine enumerates screens as soon as this returns, and
        # in that gap it saw the real screen still on and streamed it (a 21:9 profile came out 1920x1200). Wait
        # until SunVD is the only screen on, at its size (up to 5 s).
        for _ in $(seq 1 20); do
            [ "$(enabled)" = "$NAME" ] && hyprctl monitors -j | python3 -c "import json,sys; m=json.load(sys.stdin); sys.exit(0 if m and m[0]['width']==${res%x*} and m[0]['height']==${res#*x} else 1)" && break
            sleep 0.25
        done
        echo "$res" > "$STATE/active"
        setsid -f "$0" watch "$(date +%s)" "$(stat -c %s "$SUNLOG" 2>/dev/null || echo 0)" >/dev/null 2>&1 < /dev/null
        log "started $res; real screens off: $(cat "$STATE/real"); on now: $(enabled)"
        ;;
    stop)   stop ;;
    watch)  watch "${2:-$(date +%s)}" "${3:-0}" ;;
    status) [ -f "$STATE/active" ] && [ -f "$MARK" ] && echo "streaming $(cat "$STATE/active") on $NAME (real: $(cat "$STATE/real"))" || echo "idle; on: $(enabled)" ;;
    "")     echo "sun-vd: no command given. Run 'sun-vd --help' for more help." >&2; exit 2 ;;
    *)      echo "sun-vd: unknown command '$1'. Run 'sun-vd --help' for more help." >&2; exit 2 ;;
esac
