#!/bin/bash

# --- Essential Environment Variables for Cron ---
# Set a more comprehensive PATH for cron
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH

# Find the current user's DBUS_SESSION_BUS_ADDRESS and DISPLAY
# This is crucial for gsettings to interact with your graphical session.
# It reliably finds the D-Bus session for the logged-in user running a GNOME session.
# If multiple users are logged in, it picks the first gnome-session found for the real user ID.
REAL_UID=$(id --real --user)
PID=$(pgrep -u "$REAL_UID" gnome-session | head -n 1)

if [ -z "$PID" ]; then
    echo "$(date): Error: Could not find an active gnome-session for user ID $REAL_UID. Is GNOME running?" >> "$HOME/wallpaper_cron.log" 2>&1
    exit 1
fi

export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ | cut -d= -f2- | tr -d '\000')

# If you encounter "Cannot open display" errors, explicitly set DISPLAY.
# This often helps if gsettings indirectly tries to use X.
export DISPLAY=:0 # Common for the primary display. If you have multiple, it might be :1, etc.

# --- Your Existing Script Logic ---
API_URL="https://api.fredagskakan.se/thisweek"
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"
WALLPAPER_NAME="fredagskakan"
WALLPAPER_FILE=""

mkdir -p "$WALLPAPER_DIR"

# Fetch JSON response
JSON_RESPONSE=$(curl -s "$API_URL")

if [ $? -ne 0 ]; then
    echo "$(date): Error: Failed to fetch JSON from API. Is 'curl' installed?" >> "$HOME/wallpaper_cron.log" 2>&1
    exit 1
fi

# Ensure 'jq' is found by using its full path or by the expanded PATH.
# If jq is in /usr/bin/jq, the PATH export above should be sufficient.
# Otherwise, use /path/to/jq or add its directory to PATH.
if ! command -v jq &> /dev/null; then
    echo "$(date): Error: 'jq' is not installed or not in PATH. Please install it using: sudo apt update && sudo apt install jq" >> "$HOME/wallpaper_cron.log" 2>&1
    exit 1
fi

IMAGE_URL=$(echo "$JSON_RESPONSE" | jq -r '.URL')
CAKE_NAME=$(echo "$JSON_RESPONSE" | jq -r '.Kaka')

if [ -z "$IMAGE_URL" ] || [ "$IMAGE_URL" == "null" ]; then
    echo "$(date): Error: Could not extract 'URL' from the JSON response." >> "$HOME/wallpaper_cron.log" 2>&1
    echo "$(date): JSON Response: $JSON_RESPONSE" >> "$HOME/wallpaper_cron.log" 2>&1
    exit 1
fi

if [ -n "$CAKE_NAME" ] && [ "$CAKE_NAME" != "null" ]; then
    WALLPAPER_NAME=$(echo "$CAKE_NAME" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]')
    WALLPAPER_FILE="$WALLPAPER_DIR/${WALLPAPER_NAME}.jpeg"
else
    WALLPAPER_FILE="$WALLPAPER_DIR/${WALLPAPER_NAME}.jpeg"
fi

echo "$(date): Image URL found: $IMAGE_URL" >> "$HOME/wallpaper_cron.log"
echo "$(date): Cake Name: ${CAKE_NAME:-N/A}" >> "$HOME/wallpaper_cron.log"

# Download the image
echo "$(date): Downloading image to $WALLPAPER_FILE..." >> "$HOME/wallpaper_cron.log" 2>&1
wget -O "$WALLPAPER_FILE" "$IMAGE_URL"

if [ $? -ne 0 ]; then
    echo "$(date): Error: Failed to download the image from $IMAGE_URL." >> "$HOME/wallpaper_cron.log" 2>&1
    exit 1
fi

# Update GNOME wallpaper setting
echo "$(date): Updating wallpaper settings with $WALLPAPER_FILE..." >> "$HOME/wallpaper_cron.log" 2>&1
gsettings set org.gnome.desktop.background picture-uri "file://$WALLPAPER_FILE" >> "$HOME/wallpaper_cron.log" 2>&1
gsettings set org.gnome.desktop.background picture-uri-dark "file://$WALLPAPER_FILE" >> "$HOME/wallpaper_cron.log" 2>&1
gsettings set org.gnome.desktop.background picture-options "zoom" >> "$HOME/wallpaper_cron.log" 2>&1

echo "$(date): Wallpaper updated successfully." >> "$HOME/wallpaper_cron.log"
