#!/bin/bash

# Get the rwall root directory
rwall_root_directory="$( dirname $( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ))"

# Navigate to the rwall root directory
cd $rwall_root_directory

# Toggles the rwall cron job in crontab
if [[ $1 == "cron-toggle" ]];
then
    # Check if rwall is already installed in crontab
    crontabGrepRwall="$(crontab -l | grep 'rwall')"
    
    # If the string is empty, then rwall is not in crontab
    if [[ $crontabGrepRwall == "" ]];
    then
        # Get the cron frequency value
        cronFrequency="$(grep cron-frequency= etc/rwall.ini | cut -f2- -d '=')"
        
        # The line to be inserted into the crontab
        cronEntry="$cronFrequency DISPLAY=:0.0 $rwall_root_directory/bin/rwall"
    
        # Add the cron entry
        (crontab -l; echo "$cronEntry") | crontab -
        
        # Create the lock file
        touch $rwall_root_directory/etc/USING-CRON.lock
    else
        # Remove the cron entry
        crontab -l | sed "\|$rwall_root_directory/bin/rwall$|d" | crontab -
        rm $rwall_root_directory/etc/USING-CRON.lock
    fi
    
    # Exit the script
    exit
fi

# Updates the cron job, if it is running
if [[ $1 == "cron-update" ]];
then
    # If it is running, toggle it off, then back on again
    # in order to pick up the new cron settings
    if [[ -e $rwall_root_directory/etc/USING-CRON.lock ]];
    then
        $($rwall_root_directory/bin/rwall cron-toggle)
        $($rwall_root_directory/bin/rwall cron-toggle)
    fi
    
    # Exit the script
    exit
fi

# Updates the settings file
if [[ $1 == "settings" ]];
then
    # Store the variables for readability
    queryString=$2              # The word(s) to use for the query
    resolution=$3               # The resolution
    wallpaperSaveDirectory=$4   # The directory to save wallpapers
    cronFrequency=$5            # The format of this parameter will be like the beginning of a cron job (ex: "0,30 * * * *")
    
    # The ini file
    iniFile=$rwall_root_directory/etc/rwall.ini
    
    # Delete the current settings file
    rm $iniFile
    
    # Create the new settings file
    echo -e "[query]\nq=$queryString\nres=$resolution\n[other]\nwallpaper-save-directory=$wallpaperSaveDirectory\n[cron]\ncron-frequency=$cronFrequency" >> $iniFile
    
    # Exit the script
    exit
fi

# Saves the current wallpaper to ~/Pictures/rwall
if [[ $1 == "save-wallpaper" ]];
then
    # The directory to save the wallpapers
    wallpaperSaveDirectory=$(grep wallpaper-save-directory= etc/rwall.ini | cut -f2- -d '=')
    wallpaperSaveDirectoryExpanded="${wallpaperSaveDirectory/#\~/$HOME}"

    # Make sure the save directory exists
    mkdir -p $wallpaperSaveDirectoryExpanded

    # If a PNG file exists, then copy that one
    if [ -e tmp/*.png ];
    then
        cp tmp/*.png $wallpaperSaveDirectoryExpanded
    else
        # Else, we're copying the JPG file
        cp tmp/*.jpg $wallpaperSaveDirectoryExpanded
    fi
    
    # Exit the script
    exit
fi



# From this point on, the normal rwall process is running



# Create the tmp directory if it doesn't already exist
mkdir -p tmp

# Remove all files in the rwall/tmp directory
rm -r tmp/*

# Read the ini file for parameters
q=$(grep q= etc/rwall.ini | cut -f2- -d '=')
res=$(grep res= etc/rwall.ini | cut -f2- -d '=')

# Download the html based on our search parameters
wget "http://wallhaven.cc/search?q=$q&categories=111&purity=100&resolutions=$res&sorting=random&order=asc" -O tmp/wallhaven.html

# grep the image ID
#id=$(grep -o -m 1 '<a href="javascript:;" data-id=".*" ' tmp/wallhaven.html | grep -o [0-9].*[0-9])
id=$(grep -oP 'wallpaper-id="\K[^"]*' tmp/wallhaven.html | head -1)

# Some variables to help us know if we found the image and what file type it is
image_found=1
file_type=""

# JPG
if [ $image_found -eq 1 ];
then
	wget_image=$(wget http://w.wallhaven.cc/full/${id:0:2}/wallhaven-$id.jpg -O tmp/wallpaper-$id.jpg)
	if [ $? -eq 0 ]
	then
		image_found=0
		file_type="jpg"
	fi
fi

# PNG
if [ $image_found -eq 1 ];
then
	wget_image=$(wget http://w.wallhaven.cc/full/${id:0:2}/wallhaven-$id.png -O tmp/wallpaper-$id.png)
	if [ $? -eq 0 ]
	then
		image_found=0
		file_type="png"
	fi
fi

# Set $DBUS_SESSION_BUS_ADDRESS enviroment variable if it is not set
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]
then
    PID=$(pidof "cinnamon")
    export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
fi

# Change the wallpaper
gsettings set org.gnome.desktop.background picture-uri "file://$rwall_root_directory/tmp/wallpaper-$id.$file_type"

