book-epub-fix.sh 1012 B

1234567891011121314151617181920212223
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. file --mime-type -b -- "$1" | grep -q ^application/zip$ || { echo not application/zip ; exit 1 ;}
  4. basedir="$(dirname -- "$1")" &&
  5. original="$(basename -- "$1" .epub)" &&
  6. cd -- "$basedir" &&
  7. twd="$(mktemp -d -- "$original".XXXX)" &&
  8. cd -- "$twd" &&
  9. unzip -q ../"$original".epub &&
  10. zip -0XrD -q out.epub mimetype &&
  11. zip -0XrD -q out.epub * -x mimetype -x out.epub &&
  12. mv out.epub ../"$original"_fix.epub &&
  13. cd .. &&
  14. rm -rf -- "$twd"
  15. # I had a lot of epubs that were made incorrectly by whoever uploaded them to the internet.
  16. # They claimed to be application/zip instead of application/epub+zip.
  17. # So I had to fix them before reading them with certain apps. I copied how to do that from stackoverflow,
  18. # then added just enough automation that it can be run from an external loop or 'find -exec'.
  19. # Remember: Epub is a zip, but it contains a mimetype file which must be added first and must not be
  20. # compressed even if the other zipped files are compressed.