#!/bin/bash

_get_icon() {
    case $1 in
    # Icons for Nerd Font
        01d) icon="";; # Clear sky - day
        01n) icon="";; # Clear sky - night
        02d) icon="";; # Few clouds (11-25%) - day
        02n) icon="";; # Few clouds (11-25%) - night
        03*) icon="";; # Scattered clouds (25-50%) - day/night
        04*) icon="";; # Broken / Overcast clouds (51-84% / 85-100%) - day/night
        09d) icon="";; # Shower rain - day
        09n) icon="";; # Shower rain - night
        10d) icon="";; # Moderate / heavy rain - day
        10n) icon="";; # Moderate / heavy rain - night
        11d) icon="";; # Thunderstorm - day
        11n) icon="";; # Thunderstorm - night
        13d) icon="";; # Snow - day
        13n) icon="";; # Snow - night
        50d) icon="";; # Fog - day
        50n) icon="";; # Fog - night
        *) icon="";;
    esac

    echo $icon
}

KEY="c93b4a667c8c9d1d1eb941621f899bb8"
CITY=""
UNITS="metric"
SYMBOL="°C"

API="https://api.openweathermap.org/data/2.5"

if [ -n "$CITY" ]; then
    if [ "$CITY" -eq "$CITY" ] 2>/dev/null; then
        CITY_PARAM="id=$CITY"
    else
        CITY_PARAM="q=$CITY"
    fi

    weather=$(curl -sf "$API/weather?appid=$KEY&$CITY_PARAM&units=$UNITS")
else
    location=$(curl -sf https://location.services.mozilla.com/v1/geolocate?key=geoclue)

    if [ -n "$location" ]; then
        location_lat="$(echo "$location" | jq '.location.lat')"
        location_lon="$(echo "$location" | jq '.location.lng')"

        weather=$(curl -sf "$API/weather?appid=$KEY&lat=$location_lat&lon=$location_lon&units=$UNITS")
    fi
fi

if [ -n "$weather" ]; then
    weather_desc=$(echo "$weather" | jq -r ".weather[0].description")
    weather_temp=$(echo "$weather" | jq ".main.temp" | cut -d "." -f 1)
    weather_icon=$(echo "$weather" | jq -r ".weather[0].icon")

    echo "$(_get_icon "$weather_icon")" " $weather_temp$SYMBOL"
else
    echo " ..."
fi
