init commit

This commit is contained in:
2026-10-10 01:17:31 -04:00
commit 9cd45cc345
7 changed files with 227 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
set -uo pipefail
shopt -s nullglob
source /etc/scan-station/env
LOG="logger -t scan-station"
ARCHIVE=/var/lib/scan-station/archive
BLANK_THRESHOLD="${BLANK_THRESHOLD:-0.003}"
# One scan at a time (ignores a second trigger mid-scan)
exec 9>/tmp/scan-station.lock
flock -n 9 || { $LOG "scan already running"; exit 0; }
# When triggered by paper being loaded, let the stack finish seating
if [ "${SCANBD_ACTION:-}" = "pageloaded" ]; then
sleep 3
fi
WORK=$(mktemp -d /tmp/scan.XXXXXX)
trap 'rm -rf "$WORK"' EXIT
STAMP=$(date +%Y-%m-%d_%H%M%S)
PDF="$WORK/scan_$STAMP.pdf"
FULL="$ARCHIVE/scan_${STAMP}_full.pdf"
DEVICE="${SCANBD_DEVICE:-fujitsu}"
mkdir -p "$ARCHIVE"
$LOG "scan started (trigger: ${SCANBD_ACTION:-manual}, device: $DEVICE)"
# scanimage exits non-zero when the feeder runs empty, which is normal
scanimage -d "$DEVICE" \
--source "ADF Duplex" --mode Color --resolution "$RESOLUTION" \
--format=png --batch="$WORK/p_%03d.png" >/dev/null 2>>"$WORK/scan.err"
# Compress PNG -> JPEG so PDFs are a few MB instead of hundreds
PNGS=("$WORK"/p_*.png)
if [ ${#PNGS[@]} -gt 0 ]; then
mogrify -format jpg -quality 70 "${PNGS[@]}" 2>>"$WORK/scan.err"
rm -f "${PNGS[@]}"
fi
PAGES=("$WORK"/p_*.jpg)
if [ ${#PAGES[@]} -eq 0 ]; then
$LOG "no pages scanned: $(tail -n1 "$WORK/scan.err")"
exit 1
fi
# Full archive copy: every page, blanks included
img2pdf --rotation="${ROTATE:-0}" "${PAGES[@]}" -o "$FULL" 2>>"$WORK/scan.err" \
|| $LOG "archive copy failed: $(tail -n1 "$WORK/scan.err")"
# Blank-page filter: fraction of dark pixels on a downscaled grayscale copy
KEEP=()
for f in "${PAGES[@]}"; do
ink=$(magick "$f" -resize 25% -colorspace Gray -threshold 80% \
-format '%[fx:1-mean]' info: 2>/dev/null)
if awk -v v="${ink:-1}" -v t="$BLANK_THRESHOLD" 'BEGIN{exit !(v<t)}'; then
$LOG "skipped blank $(basename "$f") (ink=$ink)"
else
KEEP+=("$f")
fi
done
if [ ${#KEEP[@]} -eq 0 ]; then
$LOG "all pages blank, nothing uploaded (archive: $FULL)"
exit 0
fi
if ! img2pdf --rotation="${ROTATE:-0}" "${KEEP[@]}" -o "$PDF" 2>>"$WORK/scan.err"; then
$LOG "img2pdf failed: $(tail -n1 "$WORK/scan.err")"
exit 1
fi
if curl -sS --fail --retry 3 --max-time 120 \
-H "Authorization: Token $PAPERLESS_TOKEN" \
-F "document=@$PDF;type=application/pdf" \
"$PAPERLESS_URL/api/documents/post_document/" >/dev/null 2>>"$WORK/scan.err"; then
$LOG "uploaded ${#KEEP[@]} of ${#PAGES[@]} pages"
else
cp "$PDF" /var/lib/scan-station/failed/
$LOG "upload failed, saved to /var/lib/scan-station/failed: $(tail -n1 "$WORK/scan.err")"
exit 1
fi