#!/bin/bash

DB="/var/log/cups/cupspages.db" 
OUT="/home/cups-report" 

# If you want to select a particular period, uncomment the following 
# two lines and enter the desired dates, respecting the syntax of the example.
# FROM_DATE="2026-01-13" 
# TO_DATE="2026-01-20" 

if [[ -n "${FROM_DATE:-}" && -n "${TO_DATE:-}" ]]; then
  WHERE_DATE="WHERE date(time) BETWEEN '$FROM_DATE' AND '$TO_DATE'" 
  FILE_NAME_DATE="dal-$FROM_DATE-al-$TO_DATE" 
else
  WHERE_DATE="WHERE date(time) >= date('now','-30 days')" 
  FILE_NAME_DATE="ultimi-30-giorni" 
fi

mkdir -p "$OUT" 
chown root:print-accounting "$OUT" 
chmod 2750 "$OUT" 

rm "$OUT/*" > /dev/null 2>&1|| true

# no read for other
umask 027

# CSV UTENTI - PAGINE (totale)

sqlite3 "$DB" <<EOF
.headers on
.mode csv
.output $OUT/Report_utenti_totale.csv
SELECT user AS utente, SUM(pages) AS pagine
FROM jobs
GROUP BY user
ORDER BY pagine DESC;
.output stdout
EOF

# CSV UTENTI - PAGINE (intervallo di tempo)

sqlite3 "$DB" <<EOF
.headers on
.mode csv
.output $OUT/Report_utenti_$FILE_NAME_DATE.csv
SELECT user AS utente, SUM(pages) AS pagine
FROM jobs
${WHERE_DATE}
GROUP BY user
ORDER BY pagine DESC;
.output stdout
EOF

# CSV UTENTI - PAGINE - STAMPANTI (totale + intervallo di tempo)

PRINTERS=$(sqlite3 "$DB" "SELECT DISTINCT printer FROM jobs ORDER BY printer;")

COLS="" 
TOTALS="" 
for p in $PRINTERS; do
  SAFE=$(echo "$p" | sed 's/[^a-zA-Z0-9_]/_/g')
  COLS="$COLS,
    SUM(CASE WHEN printer = '$p' THEN pages ELSE 0 END) AS '$SAFE'" 
  TOTALS="$TOTALS, SUM($SAFE)" 
done

sqlite3 "$DB" <<EOF
.headers on
.mode csv

.output $OUT/Report_utenti_stampanti_totale.csv
WITH pivot AS (
  SELECT
    user AS utente,
    SUM(pages) AS totale_pagine
    $COLS
  FROM jobs
  GROUP BY user
)
SELECT * FROM pivot
UNION ALL
SELECT
  'TOTALE',
  SUM(totale_pagine)
  $TOTALS
FROM pivot;

.output $OUT/Report_utenti_stampanti_$FILE_NAME_DATE.csv
WITH pivot AS (
  SELECT
    user AS utente,
    SUM(pages) AS totale_pagine
    $COLS
  FROM jobs
  ${WHERE_DATE}
  GROUP BY user
)
SELECT * FROM pivot
UNION ALL
SELECT
  'TOTALE',
  SUM(totale_pagine)
  $TOTALS
FROM pivot;

.output stdout
EOF
exit 0
