#!/usr/bin/env zsh

# Ref: https://gitlab.gnome.org/GNOME/gnome-shell/issues/1
function skip-crap {
    local crap_start=".*: Object [^ ]+ \(.*\), has been already finalized. Impossible to \w* any property \w* it.*"

    local crap_continue=(
        -e ".*: == Stack trace for context.*"
        -e ".*: #[0-9]+\s*0x.*"
    )

    local skip=0
    local skipped=0

    # Could probably be done more elegantly with awk/sed ?
    while read -r line; do
        if echo $line | grep -E $crap_start --quiet; then
            # echo setting skip
            skip=1
            ((skipped += 1))
            continue
        fi

        if [[ $skip == 1 ]]; then
            if echo $line | grep -E $crap_continue --quiet; then
                # echo ignoring
                ((skipped += 1))
                continue
            else
                # echo reset skip
                printf "Skipped \"already finalized\" crap ($skipped lines)\n"
                skip=0
                skipped=0
            fi
        fi

        printf "%s\n" $line
    done
}

function date-on-separate-line {
    # Use line buffering to be able to interactively grep the output
    # (sed use line buffering when stdout is tty, but doesn't detect this
    # transiently so `debug | grep foobar` will run without line buffering
    # without the stdbuf stuff)
    stdbuf -oL sed -e 's|\]:|]:\n  |'
}

# We use non-breaking space to encode newlines in multiline messages
function decode-multiline-message {
    stdbuf -oL sed -e 's| |\n    |g'
}

function gnome-shell-exe-path {
    if uname -a | grep --silent "NixOS"; then
        echo $(dirname =gnome-shell(:A))/.gnome-shell-wrapped
    else
        echo =gnome-shell
    fi
}

journalctl --follow --lines 400 $(gnome-shell-exe-path) \
    | skip-crap                \
    | date-on-separate-line    \
    | decode-multiline-message
