#!/usr/bin/env bash

# systemctl restart avahi-daemon.service

# DEVICE="pixma:MG5400_BD2FD8000000"
DEVICE="airscan:w0:CANON INC. MG5400 series"

scanimage -d "$DEVICE" --mode Gray --batch --batch-prompt --format=png --resolution=300
# scanimage -d "$DEVICE" --mode Gray --batch --format=png --button-controlled=yes --resolution=300

# ensure correct order if we scan more than 9 pages
# by adding a 0 in front of the early scans
for i in {1..9}; do
    if [ -f "out${i}png" ]; then
        mv "out${i}.png" "out0${i}.png"
        echo "Renamed out${i}.png to out0${i}.png"
    fi
done

# Find any 'out*.png' files. If none are found, exit the program.
if ! stat -t out*.png >/dev/null 2>&1; then
    echo "No 'out*.png' files found. Exiting..."
    exit 1
fi

magick out*.png out.pdf
mv out.pdf "$HOME/documents/archive/consume/$(date +'%Y-%m-%dT%H-%M')_scan.pdf"
rm out*.png