#!/bin/sh

# this path should match your system
cd /home/pi/dev/crossword

# http://www.nytimes.com/svc/crosswords/v2/puzzle/daily-2015-11-30.puz
# A URL in this form will download the puzzle in pdf format

# get the current date
puzdate=`date "+%Y-%m-%d"`

# logfile
logfile="crossword.log"

# get the login page
url="https://myaccount.nytimes.com/auth/login"
curl -f -o login.html --stderr /dev/null $url

if [ "$?" -ne 0 ]; then
	echo "Curl failed trying to fetch login page" >> $logfile
	exit 1
fi

# extract token and expires values from login page
token=`grep token login.html | sed -e 's/^.*value="\([0-9a-f]\+\)".*$/\1/'`
expires=`grep expires login.html | sed -e 's/^.*value="\([0-9a-f]\+\)".*$/\1/'`

if [ -z $token ]; then
	echo "Bad token" >> $logfile
	exit 1
fi

if [ -z $expires ]; then
	echo "Bad expiration timestamp" >> $logfile
	exit 1
fi

# keep this on the QT
# change these to your username and password
# keep '%40' in place of '@' in the e-mail address userid
userid="nobody%40example.com"
password="secret_password"

# sign in, save cookie file
curl -f -o /dev/null --stderr /dev/null -c cookies.txt \
	-d userid=$userid -d password=$password \
	-d is_continue=false -d remember=true \
	-d token=$token -d expires=$expires $url

if [ "$?" -ne 0 ]; then
	echo "Curl failed trying to sign in" >> $logfile
	exit 1
fi

nytimes=`grep -c nytimes cookies.txt`

if [ "$nytimes" -lt 1 ]; then
	echo "Bad cookies ($nytimes)" >> $logfile
	exit 1
fi

# download puzzle in .pdf format
url="http://www.nytimes.com/svc/crosswords/v2/puzzle/daily-$puzdate.pdf"
curl -f -o daily-$puzdate.pdf --stderr /dev/null -b cookies.txt $url

if [ "$?" -ne 0 ]; then
	echo "Curl failed trying to download pdf" >> $logfile
	exit 1
fi

# clean up workspace
rm -f cookies.txt
rm -f login.html

# print the puzzle
# you gotta have a line printer set up, of course
lp -d Brother daily-$puzdate.pdf

Page rendered in 0.0008 seconds.