diff --git a/src/shell/bash_functions b/src/shell/bash_functions index 1f7e786f1..1aa30c807 100755 --- a/src/shell/bash_functions +++ b/src/shell/bash_functions @@ -114,6 +114,78 @@ h() { # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +# Optimize PDF files. +# +# Usage examples: +# +# optimize-pdfs path/to/some/directory path/to/some/file ... + +optimize-pdfs() ( + + # Check if the pdfcpu command-line tool is installed. + + if ! command -v "pdfcpu" &> /dev/null; then + printf "\n%s\n\n" "pdfcpu command-line tool is not installed!" + exit + fi + + # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + get-file-size() ( + printf "%s" "$(wc -c < "$1")" + ) + + optimize-pdf() ( + filePath="$(dirname "${1%/}")" + fileName="_$(printf "%s" "$(basename "$1")" | tr '[:upper:]' '[:lower:]')" + + optimizedFilePath="$filePath/$fileName" + + printf "* %s\n" "$1" + + pdfcpu optimize "$1" "$optimizedFilePath" #&> /dev/null + + # If something went wrong (i.e. pdfcpu didn't create + # the optimized file or exited with a non-zero status) + # or the size of the optimized file is bigger than the + # original file, keep the original file. + + if [ ! -f "$optimizedFilePath" ]; then + return + fi + + # shellcheck disable=SC2181 + if [ $? -ne 0 ] || \ + [ "$(get-file-size "$1")" -le "$(get-file-size "$optimizedFilePath")" ]; + then + rm -rf "$optimizedFilePath" + return + fi + + # Otherwise, replace the original file with the optimized one. + + mv -f "$optimizedFilePath" "$1" 1> /dev/null + ) + + # ┌─ Default to the current directory. + for filePath in "${@:-.}"; do + if [ -d "$filePath" ]; then + find "${filePath%/}" \ + -depth 1 \ + -name \*.pdf \ + -print \ + -type f \ + | while read -r file; do + optimize-pdf "$file" + done + elif [ -f "$filePath" ]; then + optimize-pdf "$filePath" + fi + done +) + +# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + # Rename media files. # # Rename the specified files so the filename is the file created date