#!/bin/sh

ARTICLES="/mnt/onboard/.kobo/articles"
POCKET="/mnt/onboard/.adds/pocket"

CONVERT="${POCKET}/magick convert -limit time 60 -font ${POCKET}/fonts/DejaVuSans.ttf"
IDENTIFY="${POCKET}/magick identify -limit time 60 -quiet"

LD_LIBRARY_PATH="${POCKET}/lib:${LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH

for i in $(find $ARTICLES -type f -not -iname "*.html"); do
  FORMAT=$($IDENTIFY -format "%m" "$i")
  if [ "$FORMAT" == "GIF" ] ||
     [ "$FORMAT" == "PNG" ] ||
     [ "$FORMAT" == "SVG" ] ||
     [ "$FORMAT" == "WEBP" ]; then
    echo "Converting $i"
    $CONVERT "$i" "$i.jpg"
    if [ $? -eq 0 ]; then
      mv "$i.jpg" "${i%.jpg}"
    fi
  fi
done
