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

readonly cupsArchive="$stpRoot/secrets/cupsConfig.zip"

cupsIsInstalled() {
    util::cmdExists lpstat
}

printersAreConfigured() {
    sudo test -s /etc/cups/printers.conf
}

restoreConfig() {
    log::info "Restaurando configuración de CUPS desde secrets/cupsConfig.zip..."
    unzip -q "$cupsArchive" -d "$cupsTemp"

    sudo cp "$cupsTemp/printers.conf" /etc/cups/printers.conf
    sudo chown root:lp /etc/cups/printers.conf
    sudo chmod 600 /etc/cups/printers.conf

    if [[ -d "$cupsTemp/ppd" ]]; then
        sudo mkdir -p /etc/cups/ppd
        sudo cp -r "$cupsTemp/ppd/." /etc/cups/ppd/
        sudo chown -R root:lp /etc/cups/ppd/
        sudo chmod 644 /etc/cups/ppd/*.ppd 2>/dev/null || true
    fi

    sudo systemctl restart cups
    log::ok "Configuración de CUPS restaurada"
}

if ! cupsIsInstalled; then
    log::info "CUPS no instalado, salteando"
    exit 0
fi

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

util::requireSudo

if printersAreConfigured; then
    log::info "CUPS ya tiene impresoras configuradas, salteando restauración"
    exit 0
fi

cupsTemp="$(mktemp -d)"
trap 'rm -rf "$cupsTemp"' EXIT

restoreConfig
