#!/bin/bash

# wminfo plugin: displays weather conditions for the selected airport

# command: wminfo -p 'conky.weather.wmi EPWR' -u 6s -b#0199fe -f#ffffff
# command: wminfo -p 'conky.weather.wmi KNYC' -u 6s -b#0199fe -f#ffffff
# command: wminfo -p 'conky.weather.wmi YSSY' -u 6s -b#0199fe -f#ffffff

# Attention: EPWR in the command above is the ICAO code for Wroclaw, Poland;
# before running weather.wmi plugin find your nearest airport ICAO code.
# In order to find ICAO code go to the following site, select a state or a
# country, and then select a location: http://weather.noaa.gov/

if [ "$1" == "" ]
then
cat <<EOF
conky.weather.wmi: displays weather conditions for the selected airport
command:
    wminfo -p 'weather.wmi XXXX -u 6'
    XXXX: ICAO airport code (see: http://weather.noaa.gov/)
EOF
exit
fi

datafile="$HOME/.wminfo/conky.tmp"
tempfile="$HOME/.wminfo/.weather.$1.tmp"
counter="$HOME/.wminfo/.counter.weather.$1.tmp"
label="WEATHER"

if [ "`grep 'temperature_unit fahrenheit' $HOME/.wminfo/conky.conf`" != "" ]
then
    TempUnit="F"
else
    TempUnit=" C"
fi

if [ -z "$(grep "^${label}: " "${datafile}")" ]
then
cat <<EOF
$0: ${label} entries in conky.conf are commented.
         
         
         
         
EOF
exit
fi

if [ ! -e ${counter} ]
then
    step=1
    touch ${counter}
else
    step=2
    rm -f ${counter}
fi

weather=`grep "^${label}: " $datafile | grep $1`

weather=${weather//; /; export }
weather=${weather/${label}: /export SID=}

echo $weather > $tempfile
. $tempfile

if [ "$TME" == "" ] && [ "$PRS" == "0" ] && [ "$HUM" == "0" ]
then
cat <<EOF
conky.weather.wmi: there's no "$1" station or there's no Internet connection.
         
         
         
         
EOF
exit
fi

TME=${TME/* /}
TME=${TME/:/}

TME=${TME#000}
TME=${TME#00}
TME=${TME#0}

TME=${TME:-0}

TMZ=`date +"%z"`
TMZ=${TMZ/+0/+}
TMZ=${TMZ/-0/-}

TME=$(($TME+ $TMZ))

if [ $TME -ge 2400 ]
then
    TME=$(($TME-2400))
elif [ $TME -lt 0 ]
then
    TME=$(($TME+2400))
fi

TME="000$TME"
TME=${TME: -4:4}

if [ "`find $datafile -mtime +1`" != "" ]
then
    TME=">24h"
fi

if [ "$TMP" == "" ]
then
cat <<EOF
conky.weather.wmi: something bad happened -- no temperature.
         
         
         
         
EOF
    exit
fi

if [ $step -eq 1 ]
then
    echo "$SID $TME"
    if [ $TMP -lt 0 ]
    then
	echo "TMP:$TMP$TempUnit"
    else
	echo "TMP: $TMP$TempUnit"
    fi
    echo "PRS: $PRS"
    echo "HUM: $HUM%"
    echo "WND: $WDS"
elif [ $step -eq 2 ]
then
    echo "$SID $TME"
    if [ "$WTH" != "" ]
    then
	echo "WTH: $WTH"
    else
	echo "SKY: $SKY"
    fi
    echo "PRS: $PRS"
    echo "HUM: $HUM%"
    echo "WND: $WDD"
fi

