#!/bin/sh

#   luci-theme-kucat
#   Copyright (C) 2019-2025 The Sirpdboy Team <herboy2008@gmail.com> 
# 
#   Have a bug? Please create an issue here on GitHub!
#       https://github.com/sirpdboy/luci-theme-kucat/issues
# 
# Licensed to the public under the Apache License 2.0

# author github@sirpdboy

kucat='kucat'
[ -s "/etc/config/advancedplus" ] &&kucat='advancedplus'
background="$(uci -q get $kucat.@basic[0].background || echo '0')"
KUCATTMP="/var/kucat_date_${background}.tmp"
BGURL="/www/luci-static/kucat/img/down${background}.jpg"
REBGURL="/luci-static/kucat/img/down${background}.jpg"
DFBGURL="/luci-static/kucat/img/bg1.jpg"
WRLOCK="/var/lock/kucat_lock_${background}.lock"

test_url() {
	url=$1
	local status=$(/usr/bin/curl -I -o /dev/null -skL --connect-timeout 1 --retry 1 -w %{http_code} "$url")
	case "$status" in
		204|\
		200)
			echo '1'
		;;
	esac
}

curl_bgurl() {
	case "$background" in
	1)
		local ppath=`curl -s 'https://open.iciba.com/dsapi/' | jsonfilter -qe '@.picture4'`
		[ -n "${ppath}" ] && echo "$ppath"
		;;
	2)
		curl -fks --max-time 3 \
		    --header "Authorization: Client-ID kmFIroj2ELqXJPtC0XUoyww-Tr_lDU8Ho8uxjptIrCo" \
		   "https://api.unsplash.com/photos/random?count=1&orientation=landscape" |
		   jsonfilter -e "@[0]['urls']['regular']"
		;;
	3)
		local ppath=`curl -s  "https://www.bing.com/HPImageArchive.aspx?format=js&n=1" |jsonfilter -qe '@.images[0].url'`
		[ -n "${ppath}" ] && echo "https://www.bing.com${ppath}"
		;;
	4)
		local i=`awk 'BEGIN{srand();print int(rand()*8)}'`
		local j=`awk 'BEGIN{srand();print int(rand()*200)}'`
		local ppath=`curl -s "http://wp.birdpaper.com.cn/intf/search?content=4k&pageno=$j&count=9" | awk -F '\"count\":9' '{print $2}' | awk -F ',\"processTime\"' '{print $1}' | sed 's#,#{#' |  jsonfilter -e "@.list[$i].url"`
		[ -n "${ppath}" ] && echo "$ppath"
		;;
	5)
		curl -fks --max-time 3 \
            "https://wallhaven.cc/api/v1/search?resolutions=1920x1080&sorting=random" |
            jsonfilter -qe '@.data[0].path'
		;;

	esac
}

bgurl_down() {
    local lock="$WRLOCK"
    exec 200>$lock
    if flock -n 200 >/dev/null 2>&1; then
		local bgurl="$(curl_bgurl)"
		if [ -n "$bgurl" ]; then
			rm -rf $BGURL
			curl -kLfsm 3 $bgurl -o $BGURL
			date +%Y%m%d > $KUCATTMP
		fi

        flock -u 200 >/dev/null 2>&1
    fi
    [ -s "$BGURL" ] && echo -ne $REBGURL || echo -ne $DFBGURL
}

check_url() {
	if [ -s $KUCATTMP ]; then
		localtime=`cat $KUCATTMP | grep $(date +%Y%m%d) `
		if [ $localtime ]; then
		   if  [ -s $BGURL ] ; then
	   	        echo -ne $REBGURL 
                        return
            fi
            fi
        fi
# local checknet=$(test_url "https://www.baidu.com")
checknet=`ping -c 1 -W 1 223.5.5.5 > /dev/null 2>&1 &&echo 1 || echo 2`
if [ "x$checknet" == "x1" ]; then 
	bgurl_down
else
	[ -s "$DFBGURL" ] && echo -ne $DFBGURL
fi
}

check_url