#!/bin/bash -e

api_response="$(curl -sS https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY)"
filename="$HOME/Pictures/apod/$(echo -n $api_response | jq --join-output '.date+" "+.title').jpg"
wallpaper_filename="$HOME/Pictures/wallpaper"
url="$(echo -n $api_response | jq --raw-output '.hdurl')"
screen_size="$(xrandr --screen 0 | grep '^Screen' | grep -Eo 'current [0-9]+ x [0-9]+' | sed -E 's/current ([0-9]+) x ([0-9]+)/\1x\2/g')"

mkdir -p "$(dirname $filename)"

if [[ -f "$filename" ]]; then
    echo "Image already downloaded"
else
    curl -sS -o "$filename" "$url"
fi

if [[ "$1" == "--wallpaper" ]]; then
    [[ -f "$wallpaper_filename" ]] && rm "$wallpaper_filename"
    img_size="$(identify "$filename" | grep -Eo '[0-9]+x[0-9]+' | head -n 1)"
    if [[ "$(echo "$img_size" | grep -Eo '^[0-9]+')" -lt "$(echo "$screen_size" | grep -Eo '^[0-9]+')" 
       || "$(echo "$img_size" | grep -Eo '[0-9]+$')" -lt "$(echo "$screen_size" | grep -Eo '[0-9]+$')" ]]; then
        convert "$filename" -filter Lanczos -gravity center -unsharp 0x1 -resize "$screen_size^" "$wallpaper_filename"
    else
        ln -s "$filename" "$wallpaper_filename"
    fi
    feh --bg-fill "$wallpaper_filename"
fi
