#!/bin/sh -e 
if [[ ! -x /usr/bin/awww ]]; then
    echo "required awww please install with yay -S awww" >&2
    exit 0
fi

# setting paths
offset=0
[[ "$1" =~ [1-9][0-9]*$ ]] && offset=$1

BACKGROUNDS_DIR="$HOME/Sync/Shared/wallpapers"
CURRENT_BACKGROUND_LINK="$HOME/.local/state/omarchy/current/background"

url_preffix="http://www.bing.com"
xml_url="https://cn.bing.com/HPImageArchive.aspx?format=xml&idx=$offset&n=10&nc=1612409408851&pid=hp&FORM=BEHPTB&uhd=1&uhdwidth=3840&uhdheight=2160"
[ -d $BACKGROUNDS_DIR ] || mkdir -p $BACKGROUNDS_DIR

# actual script
url_suffix=$(curl --no-progress-meter $xml_url | xmllint --xpath "string(//url)" -) && \
    url="$url_preffix$url_suffix"

if [[ ! -z "$url_suffix" ]]; then
    name=$(echo $url_suffix | awk -F'&' '{print $1}' | awk -F'=' '{print $2}')
    if [ ! -z "$name" ]; then 
        file_path="$BACKGROUNDS_DIR/$name"
        echo "Wallpaper name: $name"
    fi
fi

if [[ -z "$file_path" || -z "$url" ]]; then 
    exit 1
fi

if [[ ! -f "$file_path" ]]; then
    if curl "$url" -o "$file_path" 2>/dev/null; then 
        echo "Downloaded"
    else
        exit 1
    fi
fi

ln -nsf $file_path $CURRENT_BACKGROUND_LINK && \
    setsid uwsm app -- awww img $CURRENT_BACKGROUND_LINK && \
    exit 0

# return exitcode if above crashed
exit 1
