#!/usr/bin/env python3
# bing_background.py - downoads the bing homepage background and sets it as the
#                      desktop backgroud.

import logging
import os
from urllib.request import urlopen
import time

from bs4 import BeautifulSoup
from selenium import webdriver
from pyvirtualdisplay import Display


def download_link(directory, link):
    logging.info('Downloading %s', link)
    download_path = os.path.join(directory, os.path.basename(link))
    # Download the img
    with urlopen(link) as image, open(download_path, 'wb') as f:
        f.write(image.read())


def change_wp(directory, link):
    # Changes wallpaper for Unity / Gnome desktop
    desktop = os.environ.get("DESKTOP_SESSION")
    if desktop in ["gnome", "ubuntu", "unity"]:
        img_path = os.path.join(directory, os.path.basename(link))
        command = "gsettings set org.gnome.desktop.background picture-uri file://{}".format(img_path)
        os.system(command)
    else:
        logging.error('No command to change wallpaper.')


def setup_download_dir(save_dir):
    download_dir = os.path.join(os.getcwd(), save_dir)
    if not os.path.exists(download_dir):
        os.mkdir(download_dir)
    return download_dir


def main():
    # set up logging
    logging.basicConfig(filename='bing_bg.log', filemode='w', level=logging.INFO,
                        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)

    url = "https://www.bing.com/"
    save_dir = "images"
    dl_dir = setup_download_dir(save_dir)

    # set up a virtual display to use with selenium
    display = Display(visible=0, size=(800, 600))
    display.start()

    driver = webdriver.Firefox()
    driver.get(url)
    logging.info('Downloading page %s...' % url)
    time.sleep(4) #hacky sleep to allow bing homepage to load so we can grab the image

    # Parse the bing homepage
    soup = BeautifulSoup(driver.page_source, "html.parser")

    # clean up browser and stop virtual display
    driver.quit() # seems to spit out "'NoneType' object has no attribute 'path'"
    display.stop()

    # Find the URL elements
    link = soup.find_all('div', {'id': 'bgDiv'})[0].attrs['style']
    img_link = link[(link.find('url("')+5):link.find('");')]

    # Download and change wallpaper
    download_link(dl_dir, img_link)
    change_wp(dl_dir, img_link)


if __name__ == "__main__":
    main()

@@ -352,49 +352,8 @@
 k):%0A
-    logging.info('Downloading %25s', link)%0A
     
@@ -426,25 +426,235 @@
   # 
-Download the img%0A
+Check if file already exists%0A    if os.path.exists(download_path):%0A        logging.info('File %7B%7D already exists, skipping.'.format(link))%0A    else:%0A    # Download the img%0A        logging.info('Downloading %7B%7D'.format(link))%0A    
     
@@ -714,16 +714,20 @@
 ) as f:%0A
+    
         
@@ -1844,24 +1844,56 @@
 ay.start()%0A%0A
+    # Launch a Firefox instance%0A
     driver =
@@ -1972,21 +1972,24 @@
 age 
-%25s...' %25 
+%7B%7D'.format(
 url)
+)
 %0A   
@@ -2000,17 +2000,17 @@
 e.sleep(
-4
+6
 ) #hacky
@@ -2469,16 +2469,68 @@
 ('%22);')%5D
+%0A    logging.info('Found link: %7B%7D'.format(img_link))
 %0A%0A    # 

Implement check for existing file