#!/bin/bash
# $ ./weatherinfo.sh weatherinfo.conf
# Gets the current conditions from the Forecast.io (DarkSky) API
# Pulls the JSON apart using 'jq' and dumps the temperature and
# humidity values out.
# https://github.com/smeek/darksky
# https://darksky.net/dev/register
#
# Adapted SkyLine, June 2018.
#

#
# Check dependencies
#
if ! command -v curl >/dev/null 2>&1; then
    echo "\"cURL\" is required but not installed; try \"apt-get install curl\" and try again. Abort."
    exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
    echo "\"jq\" is required but not installed; try \"apt-get install jq\" and try again. Abort."
    exit 1
fi

if ! command -v sox >/dev/null 2>&1; then
    echo "\"SoX\" is required but not installed; try \"apt-get install sox libsox-fmt-mp3\" and try again. Abort."
    exit 1
fi

#
# Helper Functions
#
function strip_quotes {
    tmp=$1
    tmp="${tmp%\"}"
    tmp="${tmp#\"}"
    echo $tmp
}

#
# Parse the config file
# {
#     "latitude": <number>, /* 44.8860 */
#     "longitude": <number>, /* 36.0961 */
#     "apiKey": <string>, /* 052cadd53fc0f5665554f0154444a003 */
#     "language": <string>, /* uk */
#     "units": <string> /* si */
# }
#
CONFIG_FILE=$1
#echo "Config. File: $CONFIG_FILE"
if [ "$CONFIG_FILE" = "" ]; then
    echo "Configuration file not specified. Abort."
    exit 2
fi

CONFIG=$(cat $CONFIG_FILE)
#echo "Config.: $CONFIG"
LAT=$(echo $CONFIG | jq '.latitude')
LONG=$(echo $CONFIG | jq '.longitude')
#echo "Lat./Long.: $LAT,$LONG"
API_KEY=$(echo $CONFIG | jq '.apiKey')
API_KEY=$(strip_quotes $API_KEY)
#echo "API Key: $API_KEY"
LANG=$(echo $CONFIG | jq '.language')
LANG=$(strip_quotes $LANG)
#echo "Language: $LANG"
UNITS=$(echo $CONFIG | jq '.units')
UNITS=$(strip_quotes $UNITS)
#echo "Units: $UNITS"

#
# Query the API
#
API_URI=https://api.darksky.net/forecast
RSP=`curl -sS "${API_URI}/${API_KEY}/${LAT},${LONG}?lang=${LANG}&units=${UNITS}&exclude=minutely,daily,alerts"`
#echo "Response: $RSP"
CURRENTLY=$(echo $RSP | jq '.currently')
HOURLY=$(echo $RSP | jq '.hourly')
#echo "Currently: $CURRENTLY"
#echo "Hourly: $HOURLY"
SUMMARY=$(echo $CURRENTLY | jq -r '.summary')
TEMPERATURE0=$(echo $CURRENTLY | jq -r '.temperature' )
TEMPERATURE=$(echo $TEMPERATURE0 | awk '{printf "%.0f\n",$1}')
HUMIDITY0=$(echo $CURRENTLY | jq -r '.humidity')
HUMIDITY=$(echo $HUMIDITY0*100 | bc | awk '{printf "%.0f\n",$1}')
PRESSURE0=$(echo $CURRENTLY | jq -r '.pressure')
#Тиск перетворений в "мм" та обчислений "Барометричною Формулою", при 95м. над рівнем моря
#Потрібно зкоригувати під ваші умови...
PRESSURE=$(echo $PRESSURE0*0.750064*'e((-0.029*9.81*95)/(8.31*('$TEMPERATURE0'+273)))' | bc -l | awk '{printf "%.0f\n",$1}')

WindBearing=$(echo $CURRENTLY | jq -r '.windBearing')
WindSpeed=$(echo $CURRENTLY | jq -r '.windSpeed' | awk '{printf "%.0f\n",$1}')
WindGust=$(echo $CURRENTLY | jq -r '.windGust' | awk '{printf "%.0f\n",$1}')

CurrentTime=$(echo $CURRENTLY | jq -r '.time')

SUMMARY3=$(echo "$HOURLY" | jq -r '.data[3].summary')
TEMPERATURE3=$(echo "$HOURLY" | jq -r '.data[3].temperature' | awk '{printf "%.0f\n",$1}')
WindSpeed3=$(echo $HOURLY | jq -r '.data[3].windSpeed' | awk '{printf "%.0f\n",$1}')

RSPTIZ=$(echo "$RSP" | jq -r '.timezone')
CurrentUnixTime=$(echo "$RSP" | jq -r '.currently.time')
CurrentTime=$(TZ=$RSPTIZ date --date="@$CurrentUnixTime" '+%H %M')

#
# Розрахунок напрямку вітра
#
if [[ "${WindBearing:0:1}" != [0-9] ]]; then
	: # ignore NA wind direction
elif [[ "${WindBearing}" -ge 23 && "${WindBearing}" -le 67 ]]; then
	WindBearing=$(echo північно-східний)
elif [[ "${WindBearing}" -ge 68 && "${WindBearing}" -le 112 ]]; then
	WindBearing=$(echo східний)
elif [[ "${WindBearing}" -ge 113 && "${WindBearing}" -le 157 ]]; then
	WindBearing=$(echo південно-східний)
elif [[ "${WindBearing}" -ge 158 && "${WindBearing}" -le 202 ]]; then
	WindBearing=$(echo південний)
elif [[ "${WindBearing}" -ge 203 && "${WindBearing}" -le 247 ]]; then
	WindBearing=$(echo південно-західний)
elif [[ "${WindBearing}" -ge 248 && "${WindBearing}" -le 292 ]]; then
	WindBearing=$(echo західний)
elif [[ "${WindBearing}" -ge 293 && "${WindBearing}" -le 337 ]]; then
	WindBearing=$(echo північно-західний)
else
	WindBearing=$(echo північний)
fi

#echo "CurrentUnixTime: $CurrentUnixTime"
#echo "CurrentTime: $CurrentTime"
#echo "Summary: $SUMMARY"
#echo "Temperature: $TEMPERATURE°C"
#echo "Pressure: $PRESSUREмм"
#echo "Humidity: $HUMIDITY%"
#echo "WindBearing: $WindBearing"
#echo "WindSpeed: $WindSpeedм/с"
#echo "WindGust: $WindGustм/с"
#cho "Summary3: $SUMMARY3"
#echo "Temperature3: $TEMPERATURE3°C"
#echo "WindSpeed3: $WindSpeed3м/с"

WeatherCurrent=$(echo Станом на $CurrentTime в місті Запоріжжя: $SUMMARY, температу́ра-$TEMPERATURE° при атмосферному тиску-$PRESSUREмм, і вологості-$HUMIDITY%, вітер $WindBearing $WindSpeedм/с.)
Weather3=$(echo В найближчі 3 години: $SUMMARY3, температу́ра-$TEMPERATURE3°, вітер $WindSpeed3м/с.)
AudioDir=/var/spool/svxlink/weatherinfo
#echo "WeatherCurrent: $WeatherCurrent"
#echo "Weather3: $Weather3"
#echo "AudioDir: $AudioDir"

sleep 2
wget -q -U Mozilla -O $AudioDir/WeatherCurrent.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=$WeatherCurrent&tl=uk"
wget -q -U Mozilla -O $AudioDir/Weather3.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=$Weather3&tl=uk"
sox $AudioDir/WeatherCurrent.mp3 $AudioDir/Weather3.mp3 -r16000 -esigned-integer -b16 -c1 $AudioDir/weather.wav tempo 1.1

#mpg123 $AudioDir/WeatherCurrent.mp3
#mpg123 $AudioDir/Weather3.mp3

