#!/bin/bash

# This script will currently only run on macOS (macOS specific wallpaper command is used)
# The rest of the script will run on regular unix machines, providing you have
# bash, curl and jq installed.

set -euo pipefail

CURL="$(which curl) -s -H \"User-Agent: wallpaper script (/u/pingiun)\""
TMPDIR=$(mktemp -d)
$CURL "https://www.reddit.com/r/wallpaper/top.json" > $TMPDIR/top.json
for i in {0..4}; do
 URL=$(/usr/local/bin/jq -r ".data.children[$i].data.url" $TMPDIR/top.json)
 PARTS=(${URL//\// })
 FILE=${PARTS[${#PARTS[@]}-1]}
 FILEPATH="$HOME/wallpaper/$FILE"
 $CURL $URL > "$FILEPATH"
 if file "$FILEPATH" | grep -qE 'image|bitmap'; then
   # macOS specific command:
   osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$FILEPATH\""
   exit
 fi
done