#!/usr/bin/env python3
import os
import subprocess
from datetime import datetime

import requests

today = datetime.today().strftime("%Y-%m-%d")
home = os.path.expanduser("~")
target_path = f"{home}/var/backgrounds/bing/{today}.jpg"

# If the file for today already exists, just exit
if os.path.isfile(target_path):
    print(f"Bing image for {today} already exists, skipping download")
    exit()

iotd_uri = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1"
r = requests.get(iotd_uri)
image_info_uri = r.json()["images"][0]["url"]
img = requests.get(f"https://www.bing.com{image_info_uri}", stream=True)

handle = open(target_path, "wb")
for chunk in img.iter_content(chunk_size=512):
    if chunk:  # filter out keep-alive new chunks
        handle.write(chunk)
