#!/bin/sh
# Stock restore: system upgrade (no args) or package uninstall (--uninstall).
set -eu

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

DATADIR=/usr/share/harbour-muoto
UNINSTALL=false
ICON_WAIT_SEC=180

for arg in "$@"; do
    case "$arg" in
        --uninstall)
            UNINSTALL=true
            ICON_WAIT_SEC=60
            ;;
        -h|--help)
            echo "Usage: harbour-muoto-oneshot-restore [--uninstall]" >&2
            exit 0
            ;;
        *)
            echo "harbour-muoto-oneshot-restore: unknown option: $arg" >&2
            exit 2
            ;;
    esac
done

# 1) Fonts (conf + Sailjail staging under ~/.local/share/fonts/muoto)
muoto_dconf_as_user_or_die "dconf write /apps/harbour-muoto/activeFontPack \"'default'\""
muoto_run_as_user_or_die 'rm -f ~/.config/fontconfig/conf.d/99-muoto.conf; rm -rf ~/.local/share/fonts/muoto; fc-cache -f'

# 2) Icons — launcher session RestoreIcons (always on upgrade/uninstall)
# Dyn flags off before RestoreIcons so the daemon's final rebuild is stock-static.
# RestoreIcons itself does not clear these (Icons Default restore keeps them on).
muoto_dconf_as_user_or_die "dconf write /apps/harbour-muoto/launcher/dynamicClockEnabled false"
muoto_dconf_as_user_or_die "dconf write /apps/harbour-muoto/launcher/dynamicCalendarEnabled false"

_restore_icons_once() {
    if ! muoto_ensure_launcher_icond; then
        echo "harbour-muoto-oneshot-restore: launcher-icond not available" >&2
        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
}

_run_icon_restore() {
    if ! _restore_icons_once; then
        sleep 3
        _restore_icons_once
    fi
}

# Legacy bulk safety net (3.1 migration path).
if muoto_icons_backup_present; then
    /usr/bin/harbour-muoto-migrate-bulk-icons || true
fi

if ! _run_icon_restore; then
    echo "harbour-muoto-oneshot-restore: RestoreIcons failed" >&2
    exit 1
fi

# 3) Icons dconf
muoto_dconf_as_user_or_die "dconf write /apps/harbour-muoto/activeIconPack \"'default'\""
muoto_dconf_as_user_or_die "dconf write /apps/harbour-muoto/iconOverlay false"

# 4) Silica density
muoto_dconf_as_user_or_die "dconf reset /desktop/sailfish/silica/theme_pixel_ratio"
muoto_dconf_as_user_or_die "dconf reset /desktop/sailfish/silica/icon_size_launcher"

# 5) Vendor dconf locks
for f in silica-configs.txt ui-configs.txt; do
    bk="$DATADIR/backup/dlocks/$f.bk"
    dst="/etc/dconf/db/vendor.d/locks/$f"
    if [ -f "$bk" ]; then
        mv "$bk" "$dst" || true
    fi
done
dconf update || true

exit 0
