#!/usr/bin/bash
# shellcheck disable=SC1090,SC1091

# set -xv

OUTDIR="$HOME/photos/eumetsat"

# full screen coverage
# PRJ=AUTO:42004,52,5,0
# BBOX=(-6400000 -100000 6400000 7700000)

# full disk
PRJ=AUTO:42003,0,0,0
BBOX=(-12800000 -7200000 12800000 7200000)

# europe
# PRJ=AUTO:42004,0,0,0
# BBOX=(22.5 -45 90 67.5)
# BBOX=(-45 -90 180 135)
# BBOX=(-4500000 2250000 6750000 9000000)

WIDTH=1920
HEIGHT=1080

error() {
	printf "\033[31m%s\033[0m\n" "$1"
	. "$HOME/.fehbg"
	exit 1
}

[ -z "$EUMETSAT_KEY" ] && error 'make sure to set EUMETSAT_KEY to the client key'
[ -z "$EUMETSAT_SECRET" ] && error 'make sure to set EUMETSAT_SECRET to the client secret'

# verify internet
ping -c1 1.1.1.1 >>/dev/null || error "couldn't establish an internet connection!"

# acquire the API key
key=$(
	curl -k -d "grant_type=client_credentials" \
		-H "Authorization: Basic $(printf "%s:%s" "$EUMETSAT_KEY" "$EUMETSAT_SECRET" | base64)" \
		https://api.eumetsat.int/token | jq -r '.["access_token"]'
)

# set url
url="https://view.eumetsat.int/geoserver/wms?"
url+="&service=WMS"
url+="&request=GetMap"
url+="&version=1.3.0"
url+="&layers=mtg_fd:rgb_geocolour"
url+="&width=$WIDTH&height=$HEIGHT"
url+="&bbox=${BBOX[0]},${BBOX[1]},${BBOX[2]},${BBOX[3]}"
url+="&crs=$PRJ"
url+="&styles="
url+="&transparent=true"
url+="&format=image/png"
url+="&access_token=$key"

# process incoming data
[ ! -d "$OUTDIR" ] && { mkdir -p "$OUTDIR" || error "failed to access '$OUTDIR'!"; }
curl "$url" -o "$OUTDIR/tmp.png" || error "failed to download from url='$url'!"
mv -f "$OUTDIR/tmp.png" "$OUTDIR/curr.png"

# update the feh background
. "$HOME/.fehbg"
