#!/bin/bash

# Google Drive sharing link for the image
image_path_link="https://drive.google.com/uc?export=download&id=YOUR_FILE_ID_HERE"

# Fetch the username of the user who invoked the script
username=$(logname)

# Destination directory for the downloaded image (Downloads folder)
destination_dir="/home/$username/Downloads"

# File name for the downloaded image
# please replace the file_name by the desired wallpaper name to be set for downloaded image file
file_name="image.jpg"

# Maximum number of download attempts
max_attempts=3

# Function to download the image
download_image() {
    local attempt=1
    while [ $attempt -le $max_attempts ]; do
        echo "Attempt $attempt: Downloading image..."
        if curl -k -L -o "$destination_dir/$file_name" "$image_path_link"; then
            echo "Image downloaded successfully to: $destination_dir/$file_name"
            return 0  # Exit function with success
        else
            echo "Failed to download the image (Attempt $attempt/$max_attempts)."
            ((attempt++))
        fi
    done
    echo "Exceeded maximum number of download attempts. Failed to download the image."
    return 1  # Exit function with failure
}

# Check if the file already exists in the destination directory
if [ -f "$destination_dir/$file_name" ]; then
    echo "File '$file_name' already exists in the destination directory."
    echo "Renaming the existing file before downloading a new one..."
    # Rename the existing file with a timestamp suffix
    mv "$destination_dir/$file_name" "$destination_dir/${file_name%.jpg}_$(date +"%Y%m%d%H%M%S").jpg"
fi

# Print the destination directory for debugging
echo "Destination directory: $destination_dir"

# Create the destination directory if it doesn't exist
mkdir -p "$destination_dir"

# Call the function to download the image
download_image

# Define the path to the downloaded wallpaper image
WALLPAPER_PATH=$(realpath "$destination_dir/$file_name")

# Set the wallpaper for all users
for user in $(getent passwd | cut -d: -f1); do
    # Get the user's home directory
    user_home=$(eval echo ~$user)

    # Set the wallpaper for the user
    sudo -u $user DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u $user)/bus gsettings set org.gnome.desktop.background picture-uri "file://$WALLPAPER_PATH"
done

# Revoke permission to the X server after setting wallpaper
xhost -SI:localuser:$(whoami)