weather/client_weather.sh
2023-01-13 17:12:07 -05:00

142 lines
3.2 KiB
Bash
Executable File

#!/bin/bash
# client version, calls server for actual API info
usage() {
cat <<EOF
usage: $0 [-c COORD_PAIR][-s QUERY][-z ZIPCODE][-u <c|f>]
Queries OpenWeatherMapAPI for weather or lat/long
options:
-c, --coords searches for weather based on COORD_PAIR
-z, --zipcode returns the coordinate pair(s) for given zipcode
-s, --search returns the coordinate pair(s) for QUERY
-u, --units sets the temperature units
COORD_PAIR is a string of the format "LAT,LON"
QUERY is a city, state or city to search
EOF
}
WORKING_DIR="$HOME/.local/share/weather"
WEATHER_FILE="$WORKING_DIR/.env"
WEATHER_CALL="ssh spinach@git.keegandeppe.com weather"
TIMEOUT=60 # timeout for info
print_weather() {
# prints the weather
# check to see if it is expired
check_expiration
print "$TEMPERATURE $HUMIDITY in $CITY, $STATE\n"
# save before exiting
save_info
}
check_expiration() {
# checks if the info is expired
get_weather
}
get_location() {
# no search, use IP
if [[ -n "$SEARCH" ]] ; then
# search
echo "$SEARCH"
elif [[ -n "$ZIPCODE" ]] ; then
# zipcode
echo "$ZIPCODE"
else
# default to IP
url="http://ip-api.com/csv/?fields=252"
res=$(curl --silent -fL "$url")
LAT=$(awk -F , '{print $5}' <<<"$res")
LON=$(awk -F , '{print $6}' <<<"$res")
CITY=$(awk -F , '{print $3}' <<<"$res")
STATE=$(awk -F , '{print $1}' <<<"$res")
fi
}
get_weather() {
# calls server for weather based on $LAT, $LONG
# only update weather every 30 seconds
if [[ "$UNITS" =~ ^[Cc]$ ]] ; then
# units set to celsius
UNITS="metric"
else
# imperial
UNITS="imperial"
fi
if [[ -z "$LAT" || -z "$LON" ]] ; then
# no lat or lon
get_location
fi
WEATHER=$($WEATHER_CALL "-c $LAT,$LON -u $UNITS")
echo "$WEATHER" | gojq '.'
TEMPERATURE=$(echo $WEATHER | gojq -r '.main.temp')
HUMIDITY=$(echo $WEATHER | gojq -r '.main.humidity')
WEATHER_ICON=$(echo $WEATHER | gojq -r '.weather[0].icon')
EXPIRATION=$(($(date +%s)+$TIMEOUT))
}
save_info() {
# saves set env vars to files
printf '%s\n' \
"LAT=$LAT" \
"LON=$LON" \
"CITY=$CITY" \
"STATE=$STATE" \
"TEMPERATURE=$TEMPERATURE" \
"TEMPERATURE_ICON=$TEMPERATURE_ICON" \
"HUMIDITY=$HUMIDITY" \
"WEATHER_ICON=$WEATHER_ICON" \
"EXPIRATION=$EXPIRATION"
}
load_info() {
if [[ -e "$
# shifting longform
for arg in "$@"; do
shift
case "$arg" in
'--zipcode') set -- "$@" "-z" ;;
'--coords') set -- "$@" "-c" ;;
'--search') set -- "$@" "-s" ;;
'--units') set -- "$@" "-u" ;;
*) set -- "$@" "$arg" ;;
esac
done
while getopts "z:c:s:u:h" opt; do
case "$opt" in
'u' )
UNITS="$OPTARG"
;;
'z' )
ZIPCODE="$OPTARG"
;;
's' )
SEARCH="$OPTARG"
;;
'h' )
usage
exit 0
;;
esac
done
if [[ -n "$SEARCH" || -n "$ZIPCODE" ]] ; then
# perform search
get_location
fi
# print the weather
print_weather