Initial commit

This commit is contained in:
Dan Church 2021-06-29 11:26:43 -05:00
commit ef32d67491
Signed by: h3xx
GPG Key ID: EA2BF379CD2CDBD0
1 changed files with 105 additions and 0 deletions

105
optipdf Executable file
View File

@ -0,0 +1,105 @@
#!/bin/bash
# vi: et sts=4 sw=4 ts=4
PRESERVE_TIMESTAMP=0
TEMP_FILES=()
cleanup() {
rm -f -- "${TEMP_FILES[@]}"
}
trap 'cleanup' EXIT
file_size() {
stat \
--format='%s' \
--dereference \
-- \
"$@" \
2>/dev/null
}
# copies $2 over to $1 if $2 is smaller than $1
use_smaller() {
# if `$TEMP' isn't empty and it's of a smaller size than `$FILE',
# preserve every attribute and replace `$FILE' with `$TEMP'
local \
FILE=$1 \
TEMP=$2 \
ORIGSIZE \
TEMPSIZE
ORIGSIZE=$(file_size "$FILE")
TEMPSIZE=$(file_size "$TEMP")
if [[ -f $TEMP &&
$TEMPSIZE -gt 0 &&
$TEMPSIZE -lt $ORIGSIZE
]]; then
# Preserve attributes by copying them from the original file to the
# temporary one
chmod \
--reference="$FILE" \
-- \
"$TEMP" &&
if [[ $PRESERVE_TIMESTAMP -ne 0 ]]; then
touch \
--reference="$FILE" \
-- \
"$TEMP"
fi &&
if [[ $UID -eq 0 ]]; then
# We are root, so we can chown(1) things
chown \
--reference="$FILE" \
-- \
"$TEMP"
fi &&
cp \
--preserve=mode,ownership,timestamps \
-- \
"$TEMP" \
"$FILE"
local ERR=$?
case "$ERR" in
'0')
printf 'Optimized "%s"\n' \
"$FILE" \
>&2
;;
*)
printf 'Failed to optimize "%s"!\n' \
"$FILE" \
>&2
;;
esac
fi
# Protect against unsuccessful following file writes to our TEMP file
rm -f -- "$TEMP"
}
TEMP0=$(mktemp -t "${0##*/}.XXXXXX")
TEMP1=$(mktemp -t "${0##*/}.XXXXXX")
TEMP_FILES+=("$TEMP0" "$TEMP0")
ERRORS=0
for FILE; do
rm -f -- "$TEMP0" "$TEMP1"
if !
qpdf --stream-data=uncompress -- "$FILE" "$TEMP0" &&
qpdf --stream-data=compress -- "$TEMP0" "$TEMP1" &&
use_smaller "$FILE" "$TEMP1"; then
(( ++ERRORS ))
fi
done
if [[ $ERRORS -gt 0 ]]; then
exit 1
fi