#!/bin/sh
set -e

owm(){
    # IPINFO=$(curl -s ipinfo.io/loc)
    # LAT=$(echo $IPINFO | cut -d, -f1 | cut -d. -f1)
    # LON=$(echo $IPINFO | cut -d, -f2 | cut -d. -f1)
    INFO=$(wget -qO- ipinfo.io)
    CITY=$(echo $INFO | jq -r '.city')
    REGI=$(echo $INFO | jq -r '.region')
    COUN=$(echo $INFO | jq -r '.country')
    QUERY="$CITY, $REGI, $COUN"
    APPID=`_get-pass OpenWeatherMapAPPID`
    #{%@@ if False @@%}#
    notify-send "Get a free appid"
    xdg-open openweathermap.org &
    exit 1
    #{%@@ endif @@%}#

    FORECAST=$(wget -qO- http://api.openweathermap.org/data/2.5/forecast\?APPID\=${APPID}\&q="${CITY}"\&units\=metric)
    TEMP=$(echo $FORECAST | jq -r ".list[0].main.temp" |
        perl -pe 's/(\d*)\.\d*/\1/')
    WEATHER=$(echo $FORECAST | jq -r ".list[0].weather[0].main")

    MIN=$(echo $FORECAST | jq -r ".list[2].main.temp_min" |
        perl -pe 's/(\d*)\.\d*/\1/')
    MAX=$(echo $FORECAST | jq -r ".list[2].main.temp_max" |
        perl -pe 's/(\d*)\.\d*/\1/')

    format_weather
}

format_weather(){
    case $WEATHER in
     "Clear")
         [ $(date +%H) -gt 06 -a $(date +%H) -lt 18 ] &&
         WEATHER="" ||
         WEATHER=""
         ;;
     "Clouds")
         WEATHER=""
         ;;
     "Rain"|"Drizzle")
         WEATHER=""
         ;;
     "Mist")
         WEATHER=""
         ;;
     "Snow")
         WEATHER=""
         ;;
     "Thunderstorm")
         WEATHER=""
         ;;
    esac
}

owm_long(){
    owm

    text="$MIN $MAX  $TEMP°C $WEATHER"

    echo "$text"
}

owm_short(){
    owm

    text="$WEATHER $TEMP°C"

    echo "$text"
}

owm_pango(){
    owm

    text="$WEATHER <b>$TEMP°C</b>"

    echo "$text"
}

owm_json(){
    owm

    tee > .forecast.json <<EOF
{
    "min":"$MIN",
    "max":"$MAX",
    "temp":"$TEMP",
    "weather":"$WEATHER"
}
EOF
}

wttrin(){
    local request="wttr.in/${1-Caxias}?QF"
    [ "$(tput cols)" -lt 125 ] && request+='n'
    curl -sH "Accept-Language: ${LANG%_*}" --compressed "$request"
}

case "$1" in
    short)
        owm_short;;
    pango)
        owm_pango;;
    json)
        owm_json;;
    long)
        owm_long;;
    interactive)
        clear
        wttrin
        read -n1 -p"Press any key to quit..." ;;
    full|*)
        wttrin;;
esac
