# print the available options
help:
    just -l

local_build_dir := "_build-local"
local_prefix := env_var('HOME') / ".local"

# Build and install Scribble as a native (non-Flatpak) binary under ~/.local
local-install:
    #!/usr/bin/env sh
    set -eu
    if [ ! -d {{local_build_dir}} ]; then
        meson setup {{local_build_dir}} --prefix={{local_prefix}} -Dprofile=development
    else
        # Pick up meson.build changes (e.g. how VERSION is computed) on an
        # already-configured tree - `meson install` alone never re-runs setup.
        meson setup --reconfigure {{local_build_dir}} >/dev/null
    fi
    meson install -C {{local_build_dir}}

# Run the natively installed binary (run `just local-install` first)
local-run:
    {{local_prefix}}/bin/scribble

# Kill any running instance, rebuild, and relaunch in the background — for quick UI iteration
local-reload:
    #!/usr/bin/env sh
    set -eu
    pkill -f '{{local_prefix}}/bin/scribble$' 2>/dev/null || true
    just local-install
    nohup {{local_prefix}}/bin/scribble > /tmp/scribble.log 2>&1 &
    disown
    sleep 1
    pgrep -af '{{local_prefix}}/bin/scribble$' || echo "scribble did not start — check /tmp/scribble.log"

# Slow check that every gallery sticker keeps its dropped box (run after changing the gallery or its trimming).
gallery-test:
    cargo test load_surface_matches -- --ignored

# Drag-cost regression tests (need a display): a drag must not rebuild page textures.
perf-test:
    cargo test --release drag_perf -- --ignored

# Prints frame times while scrolling a tall document, with and without pictures (needs a display).
scroll-perf:
    cargo test --release scroll_perf -- --ignored --nocapture

# Profile a real session with `perf`: builds a release binary and runs it,
# recording until you close the window - then prints where the profile
# landed and the command to read it. Needs `just local-install` to have run
# at least once already (for `src/config.rs`'s own PKGDATADIR - a plain
# release build reuses whatever it was last configured with) and `perf`
# itself (see /proc/sys/kernel/perf_event_paranoid if it refuses to attach).
profile:
    #!/usr/bin/env sh
    set -eu
    if [ ! -f src/config.rs ]; then
        echo "src/config.rs is missing - run 'just local-install' once first." >&2
        exit 1
    fi
    cargo build --release --bin scribble
    ./target/release/scribble &
    pid=$!
    echo "Scribble running (PID $pid, release build) - use it normally, then close the window to stop recording."
    perf record -p "$pid" -g --call-graph=dwarf -o /tmp/scribble-perf.data
    echo "Profile written to /tmp/scribble-perf.data - run 'just profile-report' to see the hottest functions."

# Reads back the profile from `just profile`: the top functions by CPU
# time, each with a short call chain so it's clear whether the cost is ours
# or a system library's. Can take a while on a long session - DWARF
# call-graph unwinding isn't cheap.
profile-report:
    perf report -i /tmp/scribble-perf.data --stdio --sort=overhead,symbol,dso --percent-limit=0.5 -F overhead,symbol,dso | grep -v '^#'

# Regenerate the shape-recognition visual test report and open it in a browser
shape-test-report:
    cargo test --bin scribble -- --ignored generate_visual_test_report
    xdg-open "$HOME/scribble-shape-report.html"

# Uninstall the native binary and remove its build directory
local-clean:
    #!/usr/bin/env sh
    set -eu
    if [ -d {{local_build_dir}} ]; then
        ninja -C {{local_build_dir}} uninstall
    fi
    rm -rf {{local_build_dir}}

# Freshly build and install Flatpak on machine (Devel profile, for local testing)
install: _cargo-sources
    flatpak-builder --disable-rofiles-fuse --user --force-clean --install build-dir page.codeberg.petsoi.scribble.devel.json

# Run program inside Flatpak (build-dir must already exist — see `just install`).
# Uses `flatpak build` directly instead of `flatpak-builder --run`: the latter
# always goes through rofiles-fuse, which can't tear itself down inside a
# rootless Podman toolbox and fails with "Failure spawning rofiles-fuse".
run:
    flatpak build build-dir scribble

# Installs Scribble local as if it was built for Flathub (release profile, no Devel theme)
flathub-install: _cargo-sources
    flatpak run org.flatpak.Builder --force-clean --user --install --install-deps-from=flathub --ccache --mirror-screenshots-url=https://dl.flathub.org/media/ --repo=repo builddir page.codeberg.petsoi.scribble.json

# Builds the manifest in ../flathub the way Flathub's CI does - sandboxed,
# from the tag's tarball (so the tag must be pushed) - then lints the manifest,
# the repo and the exported metadata. Needs ../flathub on the submission branch.
# Work dirs sit under $HOME: the builder's host commands can't see /tmp.
flathub-check:
    #!/usr/bin/env sh
    set -eu
    work="$HOME/.cache/scribble-flathub-check"
    manifest=page.codeberg.petsoi.scribble.json
    cd ../flathub
    flatpak run org.flatpak.Builder --force-clean --sandbox --user --install-deps-from=flathub --ccache --mirror-screenshots-url=https://dl.flathub.org/media/ --disable-rofiles-fuse --state-dir="$work/state" --repo="$work/repo" "$work/build" "$manifest"
    flatpak run --command=flatpak-builder-lint org.flatpak.Builder manifest "$manifest"
    # The screenshots and icon are mirrored to dl.flathub.org/media only after
    # Flathub's own build, so those two errors are expected locally.
    report=$(flatpak run --command=flatpak-builder-lint org.flatpak.Builder repo "$work/repo" || true)
    echo "$report" | python3 -c 'import json,sys; ignored={"appstream-external-screenshot-url","appstream-remote-icon-not-mirrored"}; data=json.loads(sys.stdin.read() or "{}"); errors=[e for e in data.get("errors",[]) if e not in ignored]; print("\n".join(errors) or "repo lint: ok"); sys.exit(1 if errors else 0)'

# Executes all linters for Flathub
flathub-lint:
    flatpak run --command=flatpak-builder-lint org.flatpak.Builder manifest page.codeberg.petsoi.scribble.json

# Update the flatpak dependencies (needed once vendored builds are required, e.g. for Flathub submission)
flathub-update-cargo-dependencies:
    python3 helper/flatpak-cargo-generator.py Cargo.lock -o cargo-sources.json

VERSION := `grep '^version' Cargo.toml | head -1 | cut -d'"' -f2`

# Extract translatable strings into po/scribble.pot (uses `xtr`, not `xgettext` —
# the `tr!()` macro isn't a plain gettext() call xgettext understands)
pot:
    xtr src/main.rs \
        -o po/scribble.pot \
        --package-name=scribble \
        --package-version={{VERSION}} \
        --copyright-holder="Peter Sonntag" \
        --msgid-bugs-address="https://codeberg.org/petsoi/scribble/issues"

# Sync all existing .po files with the updated .pot template
update-po: pot
    #!/usr/bin/env sh
    set -eu
    for po in po/*.po; do
        [ -e "$po" ] || continue
        echo "Updating $po…"
        msgmerge --update --backup=none "$po" po/scribble.pot
    done

# Show translation completion stats for all languages
translation-stats:
    #!/usr/bin/env sh
    set -eu
    for po in po/*.po; do
        [ -e "$po" ] || continue
        lang=$(basename "$po" .po)
        printf "%-8s " "$lang"
        msgfmt --statistics "$po" -o /dev/null
    done

GPG_KEY := "5D7B4AB41FDF9F6C"

# Sign every ref in repo/ (app, appstream) with GPG_KEY and refresh its
# summary - the tail of `bundle`.
_sign-repo:
    flatpak build-update-repo repo
    flatpak build-sign repo --gpg-sign={{GPG_KEY}}
    ostree gpg-sign --repo=repo appstream/x86_64 {{GPG_KEY}}
    ostree gpg-sign --repo=repo appstream2/x86_64 {{GPG_KEY}}
    # `--prune --prune-depth=0`: keep only the newest commit of every ref
    # (prod + Devel and their .Locale/.Debug), drop every older version's
    # objects. Without it `repo/` - and the `pages` branch it's pushed to -
    # grows with every publish and is never cleaned up.
    flatpak build-update-repo --prune --prune-depth=0 --gpg-sign={{GPG_KEY}} repo

# Regenerates cargo-sources.json only when Cargo.lock changed since the last
# run (a checksum in .flatpak-builder, as file times shift on checkout): the
# generator downloads every crate to hash it.
_cargo-sources:
    #!/usr/bin/env sh
    set -eu
    stamp=.flatpak-builder/cargo-lock.sha256
    current=$(sha256sum Cargo.lock)
    if [ ! -f cargo-sources.json ] || [ "$(cat "$stamp" 2>/dev/null)" != "$current" ]; then
        just flathub-update-cargo-dependencies
        mkdir -p .flatpak-builder
        echo "$current" > "$stamp"
    fi

# Build distributable .flatpak bundle. Keeps .flatpak-builder, so the
# sources it downloaded are reused; `--disable-cache` still builds fresh.
bundle: _cargo-sources
    flatpak-builder --disable-rofiles-fuse --force-clean --disable-cache --repo=repo build-dir page.codeberg.petsoi.scribble.json
    just _sign-repo
    flatpak build-bundle repo page.codeberg.petsoi.scribble.flatpak page.codeberg.petsoi.scribble --gpg-sign={{GPG_KEY}}
    rm -rf build-dir
    @echo "Bundle ready: page.codeberg.petsoi.scribble.flatpak"
