#!/usr/bin/env bash
# Installed as /usr/lib/bluerune/bluerune-session-setup
#
# Runs in the BlueRune session before Hyprland starts (an ExecStartPre of uwsm's
# wayland-wm@bluerune\x2dhyprland.desktop.service). A user without a Hyprland config gets
# BlueRune's base config, a copy of /usr/share/bluerune/hypr, in ~/.config/hypr; without it
# Hyprland would write its own example and start with no shell. A user with the base config
# gets the package's newer copy of BlueRune's part of it at the next login.
#
# Nothing of the user's is ever overwritten:
# - A hyprland.lua that isn't the base config's, or a hyprland.conf, means the user has a
#   config of their own, and nothing is done; except the example Hyprland writes when it
#   starts without a config, while it is word for word what Hyprland wrote (left by a login
#   to plain Hyprland), which is replaced.
# - Without a config, every file of the base config that isn't there yet is copied,
#   hyprland.lua last, so a copy cut short leaves no hyprland.lua and is finished at the next
#   login. Other files already in ~/.config/hypr (hypridle.conf, a custom/*.lua of the
#   user's own) are kept as they are.
# - With the base config (hyprland.lua starts with its first line), BlueRune's part of it
#   (everything but custom/, which is the user's) is brought up to date the way
#   install-bluerune.sh does it: a file is replaced only while it is still what was last put
#   there, which the checksums in ~/.local/state/bluerune-session/base.sha256 record (or, for
#   a config the setup script installed, its manifest); one changed since is left, with a
#   word. A file the package added is copied. (Not in ~/.local/state/bluerune: anything there
#   tells the shell the user has used BlueRune before, and the welcome isn't shown.)
#
# BLUERUNE_HYPR_BASE names another source and BLUERUNE_HYPRLAND_EXAMPLE another Hyprland
# example; the tests use them.
set -euo pipefail

readonly BASE=${BLUERUNE_HYPR_BASE:-/usr/share/bluerune/hypr}
readonly EXAMPLE=${BLUERUNE_HYPRLAND_EXAMPLE:-/usr/share/hypr/hyprland.lua}
readonly HYPR=${XDG_CONFIG_HOME:-$HOME/.config}/hypr
readonly STATE=${XDG_STATE_HOME:-$HOME/.local/state}/bluerune-session/base.sha256
# install-bluerune.sh's record of what it wrote: `sha<TAB>path<TAB>checksum` lines.
readonly INSTALLED=${XDG_STATE_HOME:-$HOME/.local/state}/bluerune-install/manifest
# How the base config's hyprland.lua starts (install-bluerune.sh's BASE_MARK).
readonly BASE_MARK="-- BlueRune's base Hyprland config"
# The line Hyprland puts above its example in a config it writes, and warns about on screen.
readonly GENERATED_MARK='hl.config({ autogenerated = true }) -- remove this line to remove the warning'

say() { printf 'bluerune-session-setup: %s\n' "$*"; }

# Whether file $1 is the config Hyprland writes when it starts without one, untouched: a
# notice of comments, blank lines and GENERATED_MARK, then Hyprland's example word for word.
generated_by_hyprland() {
    local file=$1 first start line marked=0
    [[ -f $file && ! -L $file && -f $EXAMPLE ]] || return 1
    first=$(head -n1 -- "$EXAMPLE")
    start=$(grep -nxF -m1 -- "$first" "$file" | cut -d: -f1 || true)
    [[ -n $start ]] || return 1
    while IFS= read -r line; do
        if [[ $line == "$GENERATED_MARK" ]]; then
            marked=1
        elif [[ $line != --* && -n ${line//[[:space:]]/} ]]; then
            return 1
        fi
    done < <(head -n "$((start - 1))" -- "$file")
    ((marked)) && tail -n "+$start" -- "$file" | cmp -s - "$EXAMPLE"
}

# Whether file $1 is the base config's hyprland.lua (perhaps an older one).
is_base() { [[ -f $1 && ! -L $1 && $(head -n1 -- "$1") == "$BASE_MARK"* ]]; }

sum() { sha256sum <"$1" | cut -d' ' -f1; }

# Whether file $2 (the base config's $1, relative) is still what was last put there: by
# this step, or by install-bluerune.sh. bluerune-binds.lua is the exception: the setup
# script may have written a profile's own binds there, which it leaves to the user after.
last_put() {
    local rel=$1 to=$2 now
    now=$(sum "$to")
    [[ ${recorded[$rel]:-} == "$now" ]] && return 0
    [[ $rel != bluerune-binds.lua && -f $INSTALLED ]] && [[ $(awk -F'\t' -v path="$to" '$1 == "sha" && $2 == path { last = $3 } END { print last }' "$INSTALLED") == "$now" ]]
}

# The base config's files, relative, sorted, hyprland.lua last.
base_files() {
    (cd -- "$BASE" && find . -type f -printf '%P\n' | grep -vx 'hyprland.lua' | LC_ALL=C sort)
    printf 'hyprland.lua\n'
}

# Puts the base config's file $1 (relative) in place of whatever is there.
put() {
    local rel=$1 to=$HYPR/$1
    mkdir -p -- "$(dirname -- "$to")"
    cp -- "$BASE/$rel" "$to.bluerune-new"
    mv -f -- "$to.bluerune-new" "$to"
}

mode=install
if [[ ! -e $HYPR/hyprland.conf && ! -L $HYPR/hyprland.conf ]] && generated_by_hyprland "$HYPR/hyprland.lua"; then
    mode=replace
elif is_base "$HYPR/hyprland.lua"; then
    mode=update
elif [[ -e $HYPR/hyprland.lua || -e $HYPR/hyprland.conf || -L $HYPR/hyprland.lua || -L $HYPR/hyprland.conf ]]; then
    exit 0
fi
if [[ ( -e $HYPR || -L $HYPR ) && ! -d $HYPR ]]; then
    say "$HYPR is not a directory; leaving it alone."
    exit 0
fi
if [[ ! -f $BASE/hyprland.lua ]]; then
    say "the base config isn't installed in $BASE; Hyprland starts without it."
    exit 1
fi
if [[ $mode == replace ]]; then
    rm -f -- "$HYPR/hyprland.lua"
    say "replacing the example config Hyprland wrote, which nobody has changed."
fi

# What was last put in each of BlueRune's files: their checksums, by relative path.
declare -A recorded=() record=()
if [[ -f $STATE ]]; then
    while read -r checksum rel; do
        [[ -n $rel ]] && recorded[$rel]=$checksum
    done <"$STATE"
fi

copied=0 updated=0
while IFS= read -r rel; do
    to=$HYPR/$rel new=$(sum "$BASE/$rel")
    if [[ $rel == custom/* ]]; then
        # The user's: only a stub where there is none, while a config of BlueRune's is made.
        if [[ $mode != update && ! -e $to && ! -L $to ]]; then
            put "$rel"
            copied=$((copied + 1))
        fi
        continue
    fi
    if [[ ! -e $to && ! -L $to ]]; then
        put "$rel"
        copied=$((copied + 1))
    elif [[ -L $to || ! -f $to ]]; then
        continue
    elif [[ $(sum "$to") == "$new" ]]; then
        :
    elif [[ $mode == update ]] && last_put "$rel" "$to"; then
        put "$rel"
        updated=$((updated + 1))
    else
        [[ $mode == update ]] && say "$to has changes of yours, so it's left as it is; the new one is $BASE/$rel."
        [[ -n ${recorded[$rel]:-} ]] && record[$rel]=${recorded[$rel]}
        continue
    fi
    record[$rel]=$new
done < <(base_files)

state=$(for rel in "${!record[@]}"; do printf '%s  %s\n' "${record[$rel]}" "$rel"; done | LC_ALL=C sort -k2)
if [[ ! -f $STATE || $(cat -- "$STATE") != "$state" ]]; then
    mkdir -p -- "$(dirname -- "$STATE")"
    printf '%s\n' "$state" >"$STATE.new"
    mv -f -- "$STATE.new" "$STATE"
fi

# "1 file", "16 files".
files() { if (($1 == 1)); then printf '1 file'; else printf '%d files' "$1"; fi; }

if [[ $mode != update ]]; then
    say "installed BlueRune's base Hyprland config in $HYPR ($(files "$copied")). Your own settings go in $HYPR/custom/."
elif ((copied + updated > 0)); then
    say "brought BlueRune's base Hyprland config in $HYPR up to date ($(files $((copied + updated))))."
fi
