#!/bin/sh
#
# Copyright 2012 Robin * Slomkowski
# This software is available under the terms of the GPL Version 2.0 or higher
# http://www.gnu.org/licenses/gpl-2.0.txt
#
# Required software: calibre, xvfb, coreutils
#
# calibre: does the conversion to ebook format
# xvfb: is because QT requires an Xserver to run to do the rendering
# coreutils: is for the basics of the shell script
#
# The point of this script is to be run by cron to so in the morning you can
# have news to read on your or your spouses Kindle on the way to work.
#
# I do this on a Ubuntu 10.04.3 LTS (aka lucid), and use gmail to relay 
# the mail to amazon
#

#
# Default Defines
#

# I have updated my personal recipes from
# http://bazaar.launchpad.net/~kovid/calibre/trunk/files/head:/recipes/
# to keep them up to date
RECIPE_BASE='/usr/share/calibre/recipes'
# leave off the .recipe part from the name
RECIPES='bbc al_jazeera cnn'

SMTP=localhost
USER='calibre-load-news'
FROM=''
TO='YOUR_AMAZON_ID@Kindle.com'
# note this is a security issue, if on a mutli-user system the AUTH
# password IS VISABLE to all other users of the system while the mail
# goes out.
AUTH=''

#
# Main
#

# ~/.calibre-load-news.rc is for overiding the base variables above
if [ -f "$HOME/.calibre-load-news.rc" ]; then
  . "$HOME/.calibre-load-news.rc"
fi

tmp=/var/tmp/calibre-load-news.$$
re=0

mkdir $tmp

if [ -z "$*" ]; then
  _recipes="$RECIPES"
else
  _recipes="$*"
fi

if [ -z "$USER" ]; then
  _user=''
else
  _user="-u $USER"
fi

if [ -z "$AUTH" ]; then
  _auth=''
else
  _auth="-p $AUTH"
fi

if [ -z "$FROM" ]; then
  FROM="$USER"
fi

for recipe in $_recipes; do
  xvfb-run ebook-convert $RECIPE_BASE/$recipe.recipe $tmp/$recipe.mobi --title "$recipe `date +'%F %A'`" \
  && calibre-smtp -e TLS -r $SMTP $_user $_auth -a $tmp/$recipe.mobi \
    $FROM $TO $recipe \
  && rm $tmp/$recipe.mobi
  re=`expr $re + $?`
done

rmdir $tmp
exit $re

