#!/bin/bash
#
# get_temperature: polls the temperature sensor array and leaves the
# temperatures in a state file. Called by cron every 5 minutes.

TMPFILE="/tmp/temperature.XXXXXX"
STATEFILE="/var/lib/temperature/current"
DIGITEMP="/usr/bin/digitemp"
DIGICONF="/etc/digitemp.conf"

# error check #1
if ! [ -f $DIGITEMP ]; then
    echo "$DIGITEMP does not exist."
    echo "please do \"ln -snf /usr/bin/digitemp_DS9097 /usr/bin/digitemp\""
    exit 1
fi

# error check #2
if ! [ -f $DIGICONF ]; then
    echo "$DIGICONF does not exist."
    echo "please do \"/usr/bin/digitemp -i -c $DIGICONF -s /dev/ttyS0\""
    exit 1
fi

# Abort after first script error.
set -e

# Get a unique temporary tamper-proof file name.
tmp=$(mktemp $TMPFILE)

# Create a full poll list of the temperature array. This takes up to
# 5 seconds per sensor, and therefore must be done to a (slowly growing)
# temporary file.
$DIGITEMP -c $DIGICONF -a -q > $tmp
chmod 644 $tmp

# 'Atomically' move the freshly created state file in place.
mv $tmp $STATEFILE
