2012-12-07

Swedish post tracking cron job

/usr/local/bin/post-check
#!/bin/bash

# Script arguments
# argument 1 - package number, i.e. 012345670001234567
# argument 2 - mail address for package status updates
nr=$1
to=$2

# Swedish post perma-link
link="http://server.logistik.posten.se/servlet/PacTrack"
link="$link?lang=GB&xslURL=/xsl/pactrack/standard.xsl&kolliid=$1"

# Script saves status updates into temp dir
cd /tmp/

# Send the mail
# argument 1 - subject
# argument 2 - message
function send_mail() {
 # arg1 subject
 echo "$2" | mail -s "$1" \
    -a "MIME-Version: 1.0" \
    -a "Content-Type: text/html" \
    "$to"
}

# Download package latest status
wget "$link" -q -O post-status.new
if [ $? -ne 0 ]; then
 error="Could not download package status."
 echo "$error Mail sent."
 send_mail "Package $nr status error" "$error"
 exit
fi
# Make sure both current and previous status file exists
touch post-status.new
touch post-status.old

# Check if there is a difference in two last status sizes
new_size=$(stat -c%s post-status.new)
old_size=$(stat -c%s post-status.old)
if [ $new_size -ne $old_size ]; then
 echo "Package status updated. Mail sent."
 send_mail "Package $nr status updated" "`cat post-status.new`"
fi

# Save the status
cp post-status.new post-status.old

crontab -e
*/15 * * * * /usr/local/bin/post-check 012345670001234567 your@mail.com