#!/bin/bash
# TalkingWeather
# Voice playback of local weather
# Author  : Serge Le Tyrant
# License : CC-BY

twvers="1.0"

# Requires the installation (in repository) of: 
# - for the voice message: gspeech pico2wave-shell pico-tts 
# - for translation into your language (by default use the system language): crow-translate (example of a basic command: crow -b text)
# - for the weather: weather-go (example of a basic command: weather-go -hide-icon -l "Cherbourg, France")

# Other interesting utilities not used here (but data difficult to recover by script / for information purpose):
# https://www.macspots.com/get-colorful-icons-libreoffice-linux-mint
# https://wttr.in/:help
# curl wttr.in?lang=fr
# See also:
# ansiweather -l $Area


# Parameters:
# Required: either 2 parameters (1rst=language, 2nd=true for shortweather else false) OR none
# TalkingWeather $Lang, true (if shortweather wanted, else false)

# Supported languages : 
# Lang="en-GB"
# Lang="en-US"
# Lang="de-DE"
# Lang="it-IT"
# Lang="fr-FR" (default)
DefaultLang="fr-FR"
Lang=$DefaultLang
ShortWeather=false
Forecastchange=false
Forecasterror=false

# Area
Area="Querqueville, France"
#Area="Saguenay, Canada"

# TranslationEngine="libretranslate"
TranslationEngine="lingva"
# TranslationEngine="yandex"
# TranslationEngine="bing"
# TranslationEngine="google"

ForecastchangetrueMsg="Serge, the weather forecast has changed, with "
ForecastchangefalseMsg="Serge, weather forecast confirmed, with "
ForecasterrorMsg="The server of Weather forecast is unavailable"

echo "TalkingWeather: Voice playback of local weather v."$twvers
echo "help: use the -h parameter"
echo "Selected parameters: TalkingWeather "$1" "$2


# Checking input parameters (requested language, short/long weather forecast, help):

if [[ $# -eq 2 ]] && [[ $1 = "true" ]]; then
echo "TalkingWeather Lang true|false (true if shortweather wanted, else false)"
exit

elif [[ $# -eq 2 ]] && [[ $1 = "false" ]]; then
echo "TalkingWeather Lang true|false (true if shortweather wanted, else false)"
exit

elif [[ $# -eq 2 ]]; then
Lang=$1
ShortWeather=$2

elif [[ $# -eq 1 ]] && [[ $1 = "true" ]]; then
ShortWeather=true

elif [[ $# -eq 1 ]] && [[ $1 = "-h" ]]; then
echo "It requires the installation (in Arch|AUR repositories) of: gspeech pico2wave-shell pico-tts weather-go crow-translate"
echo "Launching:"
echo "TalkingWeather (without parameter)"
echo "TalkingWeather true|false (true if shortweather wanted, else false)"
echo "TalkingWeather Lang true|false (true if shortweather wanted, else false)"
echo "Lang: en-GB, en-US, de-DE, it-IT, fr-FR (default)"
exit

fi


# Working directory
Rep=$(cd $( dirname ${BASH_SOURCE[0]} ) && pwd )
if [[ -z "$Rep" ]]; then
Rep=$(pwd)
fi
#Rep=$(echo $Rep | sed 's/ /\\ /g') 
# cd "$Rep" should work but does not
# WARNING: Quotation marks are required to designate this variable so that this script works when launched from a path containing spaces
cd "$Rep"

# Query of the weather server
weather-go -hide-icon -l $Area > "$Rep"/weather.txt

# if "Weather forecast server failure"
Txt=$(cat "$Rep"/weather.txt)

if [[ $Txt =~ "response failed" ]]; then
echo $ForecasterrorMsg > "$Rep"/weather.txt
echo $ForecasterrorMsg > "$Rep"/shortweather.txt
Forecasterror=true

else

# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Some text changes ------------------------------------------------------------------------------------

# Remove the ANSI color codes (thanks to https://superuser.com/questions/380772/removing-ansi-color-codes-from-text-stream)
# Correction of color codes (addition of a space) before it deletes part of the numbers (example: [35m10.5°C=>.5°C, [1m1012.0 mbar=>12.0 mbar, [1m90.00%=> %)
sed -i -e "s/\x1b\[[0-9;]*m//g"  "$Rep"/weather.txt

# Other text takeovers
sed -i -e "s/Ick! //g"  "$Rep"/weather.txt
sed -i -e "s/Current weather is /Current weather situation: /g"  "$Rep"/weather.txt

# (I confess I'm a bit lost in all these directions :) And it is certainly possible to simplify the following (no time at the moment)
sed -i -e "s|m/s|meter per second|g"  "$Rep"/weather.txt

sed -i -e "s/second WSW/second, it comes from the West South West/g"  "$Rep"/weather.txt
sed -i -e "s/second ESE/second, it comes from the East South East/g"  "$Rep"/weather.txt
sed -i -e "s/second NNW/second, it comes from the North North West/g"  "$Rep"/weather.txt
sed -i -e "s/second NNE/second, it comes from the North North East/g"  "$Rep"/weather.txt
sed -i -e "s/second WNW/second, it comes from the West North West/g"  "$Rep"/weather.txt
sed -i -e "s/second ENE/second, it comes from the East North East/g"  "$Rep"/weather.txt
sed -i -e "s/second SSW/second, it comes from the South South West/g"  "$Rep"/weather.txt
sed -i -e "s/second SSE/second, it comes from the South South East/g"  "$Rep"/weather.txt

sed -i -e "s/second SW/second, it comes from the South West/g"  "$Rep"/weather.txt
sed -i -e "s/second SE/second, it comes from the South East/g"  "$Rep"/weather.txt
sed -i -e "s/second NW/second, it comes from the North West/g"  "$Rep"/weather.txt
sed -i -e "s/second NE/second, it comes from the North East/g"  "$Rep"/weather.txt

sed -i -e "s/second W/second, it comes from the West/g"  "$Rep"/weather.txt
sed -i -e "s/second S/second, it comes from the South/g"  "$Rep"/weather.txt
sed -i -e "s/second N/second, it comes from the North/g"  "$Rep"/weather.txt
sed -i -e "s/second E/second, it comes from the East/g"  "$Rep"/weather.txt

# ----------------

sed -i -e "s/WSW away/West South West away/g"  "$Rep"/weather.txt
sed -i -e "s/ESE away/East South East away/g"  "$Rep"/weather.txt
sed -i -e "s/NNW away/North North West away/g"  "$Rep"/weather.txt
sed -i -e "s/NNE away/North North East away/g"  "$Rep"/weather.txt
sed -i -e "s/WNW away/West North West away/g"  "$Rep"/weather.txt
sed -i -e "s/ENE away/East North East away/g"  "$Rep"/weather.txt
sed -i -e "s/SSW away/South South West away/g"  "$Rep"/weather.txt
sed -i -e "s/SSE away/South South East away/g"  "$Rep"/weather.txt

sed -i -e "s/SW away/South West away/g"  "$Rep"/weather.txt
sed -i -e "s/SE away/South East away/g"  "$Rep"/weather.txt
sed -i -e "s/NW away/North West away/g"  "$Rep"/weather.txt
sed -i -e "s/NE away/North East away/g"  "$Rep"/weather.txt

sed -i -e "s/W away/West away/g"  "$Rep"/weather.txt
sed -i -e "s/S away/South away/g"  "$Rep"/weather.txt
sed -i -e "s/N away/North away/g"  "$Rep"/weather.txt
sed -i -e "s/E away/East away/g"  "$Rep"/weather.txt

# Added text "Weather forecast:" (after a line break)
#sed -i -e "s/ mbar/ mbar. Forecast or review of this day: /g"  "$Rep"/weather.txt
sed -i -e "s/ mbar/ mbar\nForecast or review of this day: /g"  "$Rep"/weather.txt

# For good voice pronunciation
sed -i -e "s/mbar/millibar/g"  "$Rep"/weather.txt

# Removal of  ,00,0 & °C (unpleasant in voice)
sed -i -e "s/.00%/%/g"  "$Rep"/weather.txt
sed -i -e "s/.0 / /g"  "$Rep"/weather.txt
sed -i -e "s/°C/°/g"  "$Rep"/weather.txt

# We take out the useless stuff (unpleasant in voice)
sed -i -e "s/ CET//g"  "$Rep"/weather.txt

# Processing of the long version : delete 3 lines after the "Forecast" line until the end of the file
# Because for the moment, it is difficult to convert it into voice:
#"Rain chance: ▁▁ ▁▁ ▁▁          ▁▁ ▄▄ ▅▅ ▅▅ ▃▃ ▃▃ ▂▂ ▂▂ ▄▄ ▃▃
#             11a         3p          7p          11p     "
# Difficulty : these 3 lines are not always present, so this line x3 doesn't work : #sed -i '$d' "$Rep"/weather.txt
startsupp=$(echo "$(sed -n "/Forecast/=" "$Rep"/weather.txt)+3" | bc)
numberoflines=$(wc -l "$Rep"/weather.txt | cut -d ' ' -f 1)
sed -i "$startsupp,$numberoflines"d"" "$Rep"/weather.txt

# Processing of the short version : deletion of the lines before the "Forecast" line
# The short version is generated even if it is not pronounced for comparison in the next forecast
cp "$Rep/weather.txt" "$Rep/shortweather.txt"
stopsupp=$(echo "$startsupp-4" | bc)
startsupp=1
sed -i "$startsupp,$stopsupp"d"" "$Rep"/shortweather.txt

# Comparison of the current weather forecast with the previous one
# Setting ForecastchangetrueMsg if "Change in weather forecast" else ForecastchangefalseMsg="No change in weather forecast"
# ForecastchangefalseMsg="No change in weather forecast"

if cmp -s "$Rep"/shortweather.txt "$Rep"/prevshortweather.txt; then
sed -i -e "s/Forecast or review of this day: /$ForecastchangefalseMsg/g" "$Rep"/shortweather.txt
else
Forecastchange=true
cp "$Rep"/shortweather.txt "$Rep"/prevshortweather.txt 
sed -i -e "s/Forecast or review of this day: /$ForecastchangetrueMsg/g" "$Rep"/shortweather.txt
fi

# Removal of line breaks and removal of the ":" for the short version to improve continuous reading
message=$(tr '\n' ' ' < "$Rep"/shortweather.txt)
echo $message > "$Rep"/shortweather.txt
sed -i -e "s/be: /be /g" "$Rep"/shortweather.txt

# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# End of the weather forecast server response test
fi  # if [[ $Txt != "response failed" ]];


# Translation into the desired language via the selected engine ------------------------------------------------------------------------------------
if [[ $Lang != "en-US" ]] && [[ $Lang != "en-GB" ]]; then
# Google's language specification is only 2 characters long: Lang="en-GB"=>"en"
crow -e $TranslationEngine -b -t "${Lang%%-*}" -f "$Rep"/weather.txt > "$Rep"/translatedweather.txt
crow -e $TranslationEngine -b -t "${Lang%%-*}" -f "$Rep"/shortweather.txt > "$Rep"/translatedshortweather.txt
else
cat "$Rep"/weather.txt > "$Rep"/translatedweather.txt
cat "$Rep"/shortweather.txt > "$Rep"/translatedshortweather.txt
cat "$Rep"/translatedweather.txt > "$Rep"/Phonetictranslatedweather.txt
cat "$Rep"/translatedshortweather.txt > "$Rep"/Phonetictranslatedshortweather.txt
fi


# Other text takeovers (specific to French or to correct some translation/pronunciation problems) --------------------------------------------------------------------------------
if [ $Lang = "fr-FR" ]; then
sed -i -e "s/mais on a l'impression d'être à/néanmoins le ressenti est de/g"  "$Rep"/translatedweather.txt
sed -i -e "s/mais on dirait/néanmoins le ressenti est de/g"  "$Rep"/translatedweather.txt
sed -i -e "s/mais il fait/néanmoins le ressenti est de/g"  "$Rep"/translatedweather.txt
sed -i -e "s/couverture cloud/couverture nuageuse/g"  "$Rep"/translatedweather.txt
sed -i -e "s/couverture cloud/couverture nuageuse/g"  "$Rep"/translatedshortweather.txt

cat "$Rep"/translatedweather.txt > "$Rep"/Phonetictranslatedweather.txt
cat "$Rep"/translatedshortweather.txt > "$Rep"/Phonetictranslatedshortweather.txt

sed -i -e "s/mars/Mar se/g"  "$Rep"/Phonetictranslatedweather.txt
sed -i -e "s/-est/ este/g"  "$Rep"/Phonetictranslatedweather.txt
sed -i -e "s/00h00/minuit/g"  "$Rep"/Phonetictranslatedweather.txt

sed -i -e "s/n'est/nai/g"  "$Rep"/Phonetictranslatedweather.txt
sed -i -e "s/n'est/nai/g"  "$Rep"/Phonetictranslatedshortweather.txt
sed -i -e "s/tout au long/toute au long/g"  "$Rep"/Phonetictranslatedweather.txt
sed -i -e "s/tout au long/toute au long/g"  "$Rep"/Phonetictranslatedshortweather.txt
sed -i -e "s/jusqu'à/jusse cas/g"  "$Rep"/Phonetictranslatedweather.txt
sed -i -e "s/jusqu'à/jusse cas/g"  "$Rep"/Phonetictranslatedshortweather.txt
fi


# Icon associated with local weather
# icons in /usr/share/icons/gnome/48x48/status
WeatherClear=/usr/share/icons/gnome/48x48/status/weather-clear.png
PartlyCloudy=/usr/share/icons/gnome/48x48/status/weather-few-clouds.png
WeatherCloudy=/usr/share/icons/gnome/48x48/status/weather-overcast.png
WeatherLightRain=/usr/share/icons/gnome/48x48/status/weather-showers-scattered.png
WeatherShowers=/usr/share/icons/gnome/48x48/status/weather-showers.png
WeatherSnow=/usr/share/icons/gnome/48x48/status/weather-snow.png
WeatherStorm=/usr/share/icons/gnome/48x48/status/weather-storm.png
WeatherError=/usr/share/icons/gnome/48x48/places/network-server.png

Txt=$(cat "$Rep"/shortweather.txt|tr '[a-z]' '[A-Z]')

# Default
WeatherIcon=$WeatherClear

if [[ $Txt =~ "PARTLY CLOUDY" ]]; then
WeatherIcon=$PartlyCloudy
elif [[ $Txt =~ "CLOUDY" ]]; then
WeatherIcon=$WeatherCloudy
elif [[ $Txt =~ "OVERCAST" ]]; then
WeatherIcon=$WeatherCloudy
elif [[ $Txt =~ "RAIN" ]]; then
WeatherIcon=$WeatherShowers
elif [[ $Txt =~ "LIGHT RAIN" ]]; then
WeatherIcon=$WeatherLightRain
elif [[ $Txt =~ "SNOW" ]]; then
WeatherIcon=$WeatherSnow
elif [[ $Txt =~ "STORM" ]]; then
WeatherIcon=$WeatherStorm
# elif [[ $Txt =~ "RESPONSE FAILED" ]]; then 
elif [[ $Txt =~ "WEATHER FORECAST IS UNAVAILABLE" ]]; then
WeatherIcon=$WeatherError
fi


# Voice Message & display this translated weather on the screen (use tail if the file is too big, otherwise notify crashes with cat) ----------------------------------------
# If there is no change in the weather, only the short forecast is displayed without pronunciation
# If the weather server is not available for the 2nd time or more, no announcement nor jingle
#Control of variables: notify-send -i $WeatherIcon -t 80000 "Talking Weather" "ShortWeather: $ShortWeather / Forecastchange: $Forecastchange"

if [ $ShortWeather = true ] && [ $Forecastchange = true ]; then
notify-send -i $WeatherIcon -t 80000 "Talking Weather" "$(cat "$Rep"/translatedshortweather.txt)"
gspeech-cli -l $Lang -f "$Rep"/Phonetictranslatedshortweather.txt -o speech.wav && aplay speech.wav
mpg123 '/mnt/Svg2/Audio/Effets_sonores/mp3/Battle City Dendy-freeringtonesdownload.info.mp3'
elif [ $ShortWeather = true ] && [ $Forecastchange = false ] && [ $Forecasterror = false ]; then
notify-send -i $WeatherIcon -t 80000 "Talking Weather" "$(cat "$Rep"/translatedshortweather.txt)"
gspeech-cli -l $Lang -f "$Rep"/Phonetictranslatedshortweather.txt -o speech.wav && aplay speech.wav
mpg123 '/mnt/Svg2/Audio/Effets_sonores/mp3/Battle City Dendy-freeringtonesdownload.info.mp3'
elif [[ $ShortWeather = false ]]; then
notify-send -i $WeatherIcon -t 80000 "Talking Weather" "$(cat "$Rep"/translatedweather.txt)"
gspeech-cli -l $Lang -f "$Rep"/Phonetictranslatedweather.txt -o speech.wav && aplay speech.wav
mpg123 '/mnt/Svg2/Audio/Effets_sonores/mp3/Battle City Dendy-freeringtonesdownload.info.mp3'
fi


# Test
# notify-send -t 80000 "Talking Weather" "ok : $(cat "$Rep"/weather.txt)"
# exit
