#!/bin/bash
# udt-homepage: stage the homepage stylesheet and wallpaper on the dashboard host.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
#
# Staged, not installed: /opt/homepage is root-owned and this script does not
# hold root there, so it copies into ~/hp-stage/ and the steps window
# (udt-steps) carries the commands that finish the job.
#
# udt-accent starts this detached on every run, which covers both a wallpaper
# change (wallp) and a scheme switch (install.sh). Never slow and never loud
# when the host is away: a laptop off that network gets a short connect
# timeout and no steps tab, since there is nothing for the user to do.
#
# udt-accent also runs for reasons that change neither file, an icon theme
# switch for one, so what was last staged is remembered and an identical pair
# is not staged again: the finish steps would reappear for nothing.

repo="$(dirname "$(readlink -f "$0")")/.."
css="$repo/templates/homepage/custom.css"
wall="$HOME/.cache/udt/wpaper"
opts=(-q -o ConnectTimeout=5 -o BatchMode=yes)

[ -f "$css" ] && [ -e "$wall" ] || exit 0

# The wallpaper keeps its own extension, so settings.yaml has to follow it: the
# finish command rewrites its background.image line to match. The extension
# ends up in a command the user runs as root, so only known image types pass.
real="$(readlink -f "$wall")"
ext="${real##*.}"
ext="${ext,,}"
case "$ext" in
    png|jpg|jpeg|webp|gif|avif) ;;
    *) echo "homepage: $real is not a known image type, skipped" >&2; exit 1 ;;
esac
bg="background.$ext"

stamp="$HOME/.cache/udt/homepage.staged"
sum="$(cat "$css" "$real" | sha256sum)"
[ "$sum" = "$(cat "$stamp" 2>/dev/null)" ] && exit 0

scp "${opts[@]}" "$css" homepage:hp-stage/custom.css &&
    scp "${opts[@]}" "$real" "homepage:hp-stage/$bg" || {
    echo "homepage: unreachable, skipped" >&2
    exit 1
}

# Root commands, not sudo: the login user there has no sudo rights. Root's ~
# is not the staging directory, so it is named through the ssh login user,
# which ssh -G resolves from the config without connecting.
stage="~$(ssh -G homepage 2>/dev/null | awk '/^user /{print $2}')/hp-stage"
echo "$sum" > "$stamp"
out="$(
    echo "The homepage theme is staged in $stage. Finish as root on homepage:"
    echo "  cp $stage/custom.css /opt/homepage/config/"
    echo "  cp $stage/$bg /opt/homepage/public/images/"
    echo "  sed -i 's|/images/background\\.[a-z]*|/images/$bg|' /opt/homepage/config/settings.yaml"
    echo "  systemctl restart homepage"
)"
echo "$out"
printf '%s' "$out" | "$repo/bin/udt-steps" homepage
exit 0
