#!/usr/bin/env bash
set -euo pipefail
source "$stpRoot/lib/log.sh"
source "$stpRoot/lib/utils.sh"

readonly wireplumberStateDirectory="$HOME/.local/state/wireplumber"
readonly wireplumberArchive="$stpRoot/secrets/wireplumberState.zip"

wireplumberIsInstalled() {
    util::cmdExists wireplumber
}

wireplumberStateExists() {
    [[ -f "$wireplumberStateDirectory/default-nodes" ]]
}

restoreState() {
    log::info "Restaurando estado desde secrets/wireplumberState.zip..."
    mkdir -p "$HOME/.local/state"
    unzip -qo "$wireplumberArchive" -d "$HOME/.local/state"
    log::ok "Estado restaurado en: $wireplumberStateDirectory"
    log::info "Reiniciá WirePlumber para aplicar los cambios: systemctl --user restart wireplumber"
}

if ! wireplumberIsInstalled; then
    log::info "WirePlumber no instalado, salteando"
    exit 0
fi

if [[ ! -f "$wireplumberArchive" ]]; then
    log::info "Sin respaldo de estado (secrets/wireplumberState.zip), salteando"
    exit 0
fi

if wireplumberStateExists; then
    log::info "Estado de WirePlumber ya existe, salteando restauración"
    exit 0
fi

restoreState
