#!/bin/sh
# Upgrade heal for silica folder glyphs: save pack → RestoreIcons → download
# owning graphics RPMs and rpm force-install → reapply pack → disable/remove
# this unit. No healed marker; boot retries while the unit stays enabled.
# shellcheck shell=sh
set -eu

. /usr/share/harbour-muoto/service/muoto-dbus-wait.sh

DATADIR=/usr/share/harbour-muoto
SILICA=/usr/share/themes/sailfish-default/silica
UNIT=harbour-muoto-repair-folder-icons.service
STATE="$DATADIR/repair-folder-icons.state"
ICON_WAIT_SEC=180
TMPDIR=""

log() {
    echo "muoto-repair-folder-icons: $*" >&2
}

cleanup() {
    if [ -n "$TMPDIR" ] && [ -d "$TMPDIR" ]; then
        rm -rf "$TMPDIR"
        TMPDIR=""
    fi
}

self_delete() {
    # Do not use disable --now: that SIGTERMs this running oneshot.
    # rm the unit file only after this process exits — deleting it while we are
    # still MainPID makes systemd log "Current command vanished from the unit file".
    log "disabling $UNIT"
    rm -f "$STATE"
    systemctl disable "$UNIT" 2>/dev/null || true
    (
        # Wait until the oneshot shell (our parent) is gone — no sleep.
        while kill -0 "$PPID" 2>/dev/null; do
            :
        done
        rm -f /etc/systemd/system/"$UNIT"
        systemctl daemon-reload 2>/dev/null || true
    ) >/dev/null 2>&1 &
}

trap cleanup EXIT

if muoto_os_update_running; then
    log "skip (OS update in progress)"
    exit 1
fi

if ! command -v pkcon >/dev/null 2>&1; then
    log "pkcon missing"
    exit 1
fi
if ! command -v rpm >/dev/null 2>&1; then
    log "rpm missing"
    exit 1
fi

# --- 1) Save theme (persist across retries: RestoreIcons clears dconf) ---
saved_pack=$(muoto_dconf_as_user "dconf read /apps/harbour-muoto/activeIconPack" 2>/dev/null || true)
saved_pack=${saved_pack#\'}
saved_pack=${saved_pack%\'}
saved_overlay=$(muoto_dconf_as_user "dconf read /apps/harbour-muoto/iconOverlay" 2>/dev/null || true)
case "$saved_overlay" in
    true) saved_o=true ;;
    *) saved_o=false ;;
esac

if [ -z "$saved_pack" ] || [ "$saved_pack" = "default" ]; then
    if [ -f "$STATE" ]; then
        # shellcheck disable=SC1090
        . "$STATE"
        log "restored saved state pack='$saved_pack' overlay=$saved_o"
    fi
elif [ -n "$saved_pack" ] && [ "$saved_pack" != "default" ]; then
    mkdir -p "$DATADIR"
    _pack_esc=$(printf '%s' "$saved_pack" | sed "s/'/'\\\\''/g")
    printf "saved_pack='%s'\nsaved_o=%s\n" "$_pack_esc" "$saved_o" > "$STATE"
fi

log "using pack='$saved_pack' overlay=$saved_o"

# --- 2) RestoreIcons (stock launcher + folder backups if any) ---
_restore_icons_once() {
    if ! muoto_ensure_launcher_icond; then
        log "launcher-icond not available"
        return 1
    fi
    muoto_wait_op_begin RestoreIcons "$ICON_WAIT_SEC"
    if ! muoto_dbus_session_send \
        "$MUOTO_LAUNCHER_SERVICE" \
        "$MUOTO_LAUNCHER_PATH" \
        "$MUOTO_LAUNCHER_THEMES.RestoreIcons"; then
        muoto_wait_op_cancel
        return 1
    fi
    muoto_wait_op_end RestoreIcons
}

log "RestoreIcons"
if ! _restore_icons_once; then
    log "RestoreIcons failed; retry in 3s"
    sleep 3
    if ! _restore_icons_once; then
        log "RestoreIcons failed"
        exit 1
    fi
fi

# --- 3) Discover installed packages that own folder glyphs ---
pkgs=""
for z in z2.0 z1.75 z1.5-large z1.5 z1.25 z1.0; do
    for i in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16; do
        f="$SILICA/$z/icons/icon-launcher-folder-$i.png"
        [ -e "$f" ] || continue
        name=$(rpm -qf --queryformat '%{NAME}' "$f" 2>/dev/null) || continue
        case "$name" in
            *not\ owned*|*"no package"*) continue ;;
        esac
        case " $pkgs " in
            *" $name "*) ;;
            *) pkgs="$pkgs $name" ;;
        esac
    done
done

# shellcheck disable=SC2086
pkgs=$(echo $pkgs)

if [ -z "$pkgs" ]; then
    log "no owning packages found for folder icons"
    exit 1
fi

# --- 4) Refresh jolla metadata, then download + rpm force-install ---
# pkcon install --allow-reinstall alone may not rewrite already-installed files.
TMPDIR=$(mktemp -d /tmp/muoto-repair-folder-icons.XXXXXX)
log "refreshing jolla repo metadata"
if ! pkcon repo-set-data jolla refresh-now true; then
    log "jolla repo refresh failed"
    exit 1
fi

log "downloading:$pkgs → $TMPDIR"
# SFOS pkcon: download DIRECTORY PACKAGES (no --destdir).
# shellcheck disable=SC2086
if ! pkcon -y download "$TMPDIR" $pkgs; then
    log "pkcon download failed"
    exit 1
fi

# shellcheck disable=SC2012
rpm_count=$(ls "$TMPDIR"/*.rpm 2>/dev/null | wc -l | tr -d ' ')
if [ "$rpm_count" -lt 1 ]; then
    log "no RPMs in $TMPDIR after download"
    exit 1
fi

log "rpm force-install $rpm_count package(s)"
# shellcheck disable=SC2086
if ! rpm -Uvh --replacepkgs --replacefiles "$TMPDIR"/*.rpm; then
    log "rpm force-install failed"
    exit 1
fi

cleanup

# Drop any poison/legacy folder backups so the next apply seeds from real stock.
rm -rf "$DATADIR/backup/icons/folder-icons" \
       "$DATADIR/backup/folder-icons"

# --- 5) Reapply saved theme ---
if [ -n "$saved_pack" ] && [ "$saved_pack" != "default" ]; then
    log "reapplying pack='$saved_pack' overlay=$saved_o"
    # Escape single quotes for dconf string literals: 'foo' → '\''foo'\'''
    _pack_lit=$(printf '%s' "$saved_pack" | sed "s/'/'\\\\''/g")
    muoto_dconf_as_user "dconf write /apps/harbour-muoto/activeIconPack \"'${_pack_lit}'\"" || true
    muoto_dconf_as_user "dconf write /apps/harbour-muoto/iconOverlay $saved_o" || true
    if ! /usr/bin/harbour-muoto-update-icons; then
        log "update-icons / reapply failed"
        exit 1
    fi
else
    log "no pack to reapply (stock)"
fi

# --- 6) Self-delete (no healed marker) ---
self_delete
log "done"
exit 0
