#!/usr/bin/env bash
set -euo pipefail
stpRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$stpRoot/lib/log.sh"
source "$stpRoot/lib/utils.sh"

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

cupsIsInstalled() {
    util::cmdExists lpstat
}

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

copyFilesToTemporaryDirectory() {
    local temporaryDirectory="$1"
    sudo cp /etc/cups/printers.conf "$temporaryDirectory/printers.conf"
    if sudo test -d /etc/cups/ppd && sudo test -n "$(sudo ls /etc/cups/ppd/)"; then
        sudo cp -r /etc/cups/ppd "$temporaryDirectory/ppd"
    fi
    sudo chown -R "$USER" "$temporaryDirectory"
}

if ! cupsIsInstalled; then
    log::warn "CUPS no instalado"
    exit 0
fi

util::requireSudo

if ! printersAreConfigured; then
    log::warn "No hay impresoras configuradas en /etc/cups/printers.conf"
    exit 0
fi

log::step "Capturando configuración de CUPS"
mkdir -p "$stpRoot/secrets"
rm -f "$outputFile"

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

copyFilesToTemporaryDirectory "$temporaryDirectory"

(
    cd "$temporaryDirectory"
    find . -not -type d | sed 's|^\./||' | zip -q "$outputFile" -@
)

log::ok "Guardado: secrets/cupsConfig.zip ($(du -sh "$outputFile" | cut -f1))"
log::info "Impresoras respaldadas: $(lpstat -a | awk '{print $1}' | tr '\n' ' ')"
log::info "Commiteá secrets/cupsConfig.zip antes de hacer push"
