#!/bin/bash
# imprimir-duplex-configurar — asistente de configuración de Imprimir Duplex Linux.
#
# Averigua, con una prueba de dos hojas, cómo pide cada impresora la doble cara manual:
#   1. Imprime un «1» y un «3» grandes, con una flecha hacia arriba.
#   2. Pide volver a meter las dos hojas tal como han salido e imprime una «A» y una «B» detrás.
#   3. Pregunta qué letra quedó detrás del 1 y si está al derecho.
# De las respuestas deduce el gesto (TACO), el orden de las pares (ORDEN_PARES) y el giro
# (GIRAR_PARES), y los guarda en ~/.config/imprimir-duplex/<cola>.conf, que lee el backend.
#
# Uso:   imprimir-duplex-configurar [cola real]
# Sin argumento, pregunta la impresora si hay más de una con doble cara. Se lanza desde el menú
# («Configurar doble cara») o lo ofrece el backend al imprimir con una impresora sin configurar.
#
# Copyright (c) 2026 Culturoscope. Licencia MIT (ver LICENSE).

idioma=$LANG
case "$idioma" in ""|C|C.*|POSIX) idioma=$(. /etc/default/locale 2>/dev/null; echo "$LANG") ;; esac
case "$idioma" in
  es*)
    T_TITULO="Configurar doble cara"
    T_SIN_COLAS="No hay ninguna impresora de doble cara. Ejecuta antes instalar.sh."
    T_ELEGIR="¿Qué impresora configuro?"
    T_INICIO="<b>Prueba de doble cara</b> para «%s».\n\nGasta dos hojas, una sola vez. Pon papel en la bandeja y pulsa <b>Imprimir</b>."
    T_TAL="Cuando salgan las dos hojas (con un 1 y un 3), vuelve a meterlas en la bandeja <b>tal como han salido, sin darles la vuelta</b>, y pulsa <b>Continuar</b>."
    T_VUELTA="Cuando salgan las dos hojas (con un 1 y un 3), <b>dales la vuelta</b> y vuelve a meterlas en la bandeja; luego pulsa <b>Continuar</b>."
    T_DETRAS="Cuando terminen de salir, ¿qué hay detrás del <b>1</b>?"
    O_A="La letra A"; O_B="La letra B"; O_NADA="Nada: las letras salieron en la misma cara que los números"
    T_REPETIR="Hay que repetir la prueba <b>dándole la vuelta</b> a las hojas. Pon papel limpio en la bandeja y pulsa <b>Imprimir</b>."
    T_IMPOSIBLE="Las letras no salen por detrás ni dándole la vuelta a las hojas. Revisa cómo coge el papel tu impresora y vuelve a intentarlo."
    T_DERECHO="Mira la hoja del 1 por las dos caras: ¿las dos flechas apuntan hacia el mismo borde de la hoja?"
    T_LISTO="<b>Listo.</b> «Duplex-%s» ya imprime a doble cara con estos ajustes:\n\n• %s\n• Pares en orden %s%s."
    T_G_TAL="El taco se vuelve a meter tal como sale"; T_G_VUELTA="Al taco se le da la vuelta"
    T_O_DESC="descendente"; T_O_ASC="ascendente"; T_GIRO=", giradas 180º"
    B_IMPRIMIR="Imprimir"; B_CONTINUAR="Continuar"; B_SI="Sí"; B_NO="No"; B_ACEPTAR="Aceptar"
    P_ARRIBA="ARRIBA" ;;
  *)
    T_TITULO="Set up duplex"
    T_SIN_COLAS="There is no duplex printer. Run instalar.sh first."
    T_ELEGIR="Which printer should I set up?"
    T_INICIO="<b>Duplex test</b> for «%s».\n\nIt uses two sheets, only once. Load paper in the tray and press <b>Print</b>."
    T_TAL="When the two sheets come out (with a 1 and a 3), put them back in the tray <b>exactly as they came out, without flipping them</b>, and press <b>Continue</b>."
    T_VUELTA="When the two sheets come out (with a 1 and a 3), <b>flip them over</b> and put them back in the tray; then press <b>Continue</b>."
    T_DETRAS="When they come out, what is on the back of the <b>1</b>?"
    O_A="The letter A"; O_B="The letter B"; O_NADA="Nothing: the letters came out on the same side as the numbers"
    T_REPETIR="The test must be repeated <b>flipping the sheets over</b>. Load clean paper in the tray and press <b>Print</b>."
    T_IMPOSIBLE="The letters don't come out on the back even when flipping the sheets. Check how your printer takes the paper and try again."
    T_DERECHO="Look at the sheet with the 1 on both sides: do both arrows point to the same edge of the sheet?"
    T_LISTO="<b>Done.</b> «Duplex-%s» now prints on both sides with these settings:\n\n• %s\n• Even pages in %s order%s."
    T_G_TAL="The stack goes back in as it comes out"; T_G_VUELTA="The stack is flipped over"
    T_O_DESC="descending"; T_O_ASC="ascending"; T_GIRO=", rotated 180º"
    B_IMPRIMIR="Print"; B_CONTINUAR="Continue"; B_SI="Yes"; B_NO="No"; B_ACEPTAR="OK"
    P_ARRIBA="TOP" ;;
esac

ANCHO=420
z() { zenity --title="$T_TITULO" --width=$ANCHO "$@" 2>/dev/null; }
# boton <texto> <botón> → 0 si se pulsa, 1 si se cierra la ventana
boton() { [ -n "$(z --question --switch --icon-name=document-print --text="$1" --extra-button="$2")" ]; }

# --- Impresora -----------------------------------------------------------------------------------
cola="$1"
if [ -z "$cola" ]; then
  mapfile -t colas < <(LC_ALL=C lpstat -v 2>/dev/null | grep -oE 'imprimir-duplex:[^ ]+' | sed 's/^imprimir-duplex://' | sort -u)
  [ "${#colas[@]}" -gt 0 ] || { z --error --text="$T_SIN_COLAS"; exit 1; }
  if [ "${#colas[@]}" -eq 1 ]; then cola=${colas[0]}
  else cola=$(z --list --text="$T_ELEGIR" --column="" "${colas[@]}") || exit 1
  fi
fi

# --- PDF de prueba -------------------------------------------------------------------------------
# pdf_prueba <archivo> <rótulo de la página 1> <rótulo de la página 2>
# Escribe un PDF A4 de dos páginas: un rótulo enorme en el centro y, encima, una flecha hacia
# arriba con la palabra «arriba». Solo ASCII, para que las longitudes en bytes cuadren.
pdf_prueba() {
  local salida=$1; shift
  local objs=() n paginas="" i=0 rotulo contenido
  objs[1]="<< /Type /Catalog /Pages 2 0 R >>"
  objs[3]="<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>"
  n=4
  for rotulo in "$@"; do
    contenido="BT /F1 360 Tf 197 220 Td ($rotulo) Tj ET 0 0 0 RG 14 w 297 560 m 297 720 l S 297 790 m 247 715 l 347 715 l f BT /F1 28 Tf 297 520 Td -$(( ${#P_ARRIBA} * 9 )) 0 Td ($P_ARRIBA) Tj ET"
    objs[$n]="<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents $((n + 1)) 0 R >>"
    objs[$((n + 1))]="<< /Length ${#contenido} >>
stream
$contenido
endstream"
    paginas="$paginas $n 0 R"; i=$((i + 1)); n=$((n + 2))
  done
  objs[2]="<< /Type /Pages /Kids [$paginas ] /Count $i >>"
  local cuerpo="%PDF-1.4
" offsets=() k
  for ((k = 1; k < n; k++)); do
    offsets[$k]=${#cuerpo}
    cuerpo+="$k 0 obj
${objs[$k]}
endobj
"
  done
  local xref=${#cuerpo}
  cuerpo+="xref
0 $n
0000000000 65535 f
"
  for ((k = 1; k < n; k++)); do cuerpo+="$(printf '%010d 00000 n ' "${offsets[$k]}")
"; done
  cuerpo+="trailer
<< /Size $n /Root 1 0 R >>
startxref
$xref
%EOF
"
  LC_ALL=C printf '%s' "$cuerpo" > "$salida"
}

DIR=$(mktemp -d)
trap 'rm -rf "$DIR"' EXIT
export LC_ALL=C   # longitudes en bytes al montar el PDF
pdf_prueba "$DIR/frente.pdf" 1 3
pdf_prueba "$DIR/dorso.pdf" A B
unset LC_ALL
imprimir() { lp -s -d "$cola" -o sides=one-sided -t "$T_TITULO" "$1"; }

# --- Prueba --------------------------------------------------------------------------------------
TACO=tal-cual
texto_inicio=$(printf "$T_INICIO" "$cola")
while :; do
  boton "$texto_inicio" "$B_IMPRIMIR" || exit 0
  imprimir "$DIR/frente.pdf"
  [ "$TACO" = tal-cual ] && t=$T_TAL || t=$T_VUELTA
  boton "$t" "$B_CONTINUAR" || exit 0
  imprimir "$DIR/dorso.pdf"
  r=$(z --list --radiolist --text="$T_DETRAS" --column="" --column="" --hide-header \
        FALSE "$O_A" FALSE "$O_B" FALSE "$O_NADA") || exit 0
  case "$r" in
    "$O_A") ORDEN_PARES=ascendente; break ;;
    "$O_B") ORDEN_PARES=descendente; break ;;
    *)
      if [ "$TACO" = tal-cual ]; then TACO=dar-vuelta; texto_inicio=$T_REPETIR
      else z --error --text="$T_IMPOSIBLE"; exit 1; fi ;;
  esac
done
if z --question --switch --text="$T_DERECHO" --extra-button="$B_NO" --extra-button="$B_SI" | grep -qx "$B_SI"; then
  GIRAR_PARES=no
else
  GIRAR_PARES=si
fi

# --- Guardar -------------------------------------------------------------------------------------
mkdir -p "$HOME/.config/imprimir-duplex"
cat > "$HOME/.config/imprimir-duplex/$cola.conf" <<EOF
# Imprimir Duplex Linux — ajustes de «$cola», escritos por imprimir-duplex-configurar.
# Para cambiarlos, vuelve a lanzar «Configurar doble cara».
TACO=$TACO
ORDEN_PARES=$ORDEN_PARES
GIRAR_PARES=$GIRAR_PARES
EOF
[ "$TACO" = tal-cual ] && g=$T_G_TAL || g=$T_G_VUELTA
[ "$ORDEN_PARES" = descendente ] && o=$T_O_DESC || o=$T_O_ASC
[ "$GIRAR_PARES" = si ] && gi=$T_GIRO || gi=""
z --info --text="$(printf "$T_LISTO" "$cola" "$g" "$o" "$gi")" --ok-label="$B_ACEPTAR"
exit 0
